<?php
/**
 * Class Noesia Cs Admin Renderer.
 *
 * @package Noesia_Commerce_Suite
 */

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

/**
 * Presentation helper for the Noesia Commerce Suite admin shell.
 *
 * This class keeps reusable rendering helpers outside the main admin shell,
 * so modules can remain presentation-focused while the shell stays lightweight.
 */
class Noesia_CS_Admin_Renderer {
	/**
	 * Runtime dependency or state value.
	 *
	 * @var mixed
	 */
	private $container;
	/**
	 * Runtime dependency or state value.
	 *
	 * @var mixed
	 */
	private $module_registry;
	/**
	 * Runtime dependency or state value.
	 *
	 * @var mixed
	 */
	private $feature_service;
	/**
	 * Runtime dependency or state value.
	 *
	 * @var mixed
	 */
	private $system_status_service;
	/**
	 * Runtime dependency or state value.
	 *
	 * @var mixed
	 */
	private $settings_binding_service;
	/**
	 * Runtime dependency or state value.
	 *
	 * @var mixed
	 */
	private $service_boundary_service;

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $container Container.
	 * @param mixed $module_registry Module registry.
	 */
	public function __construct( Noesia_CS_Container $container = null, $module_registry = null ) {
		$this->container                 = $container;
		$this->module_registry          = $module_registry;
		$this->feature_service          = $this->service( 'feature_service' );
		$this->system_status_service    = $this->service( 'system_status_service' );
		$this->settings_binding_service = $this->service( 'settings_binding_service' );
		$this->service_boundary_service = $this->service( 'service_boundary_service' );

		if ( ! $this->feature_service && class_exists( 'Noesia_CS_Feature_Service' ) ) {
			$this->feature_service = new Noesia_CS_Feature_Service();
		}
		if ( ! $this->system_status_service && class_exists( 'Noesia_CS_System_Status_Service' ) ) {
			$this->system_status_service = new Noesia_CS_System_Status_Service();
		}
		if ( ! $this->settings_binding_service && class_exists( 'Noesia_CS_Settings_Binding_Service' ) ) {
			$this->settings_binding_service = new Noesia_CS_Settings_Binding_Service();
		}
		if ( ! $this->service_boundary_service && class_exists( 'Noesia_CS_Service_Boundary_Service' ) ) {
			$this->service_boundary_service = new Noesia_CS_Service_Boundary_Service();
		}
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $key Key.
	 */
	private function service( $key ) {
		if ( $this->container && method_exists( $this->container, 'get' ) ) {
			return $this->container->get( $key );
		}
		return null;
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $tab Tab.
	 */
	public function tab_url( $tab ) {
		$args = array(
			'page'  => 'noesia-commerce-suite',
			'tab'   => sanitize_key( $tab ),
		);

		$args = array_merge( $args, $this->dashboard_date_query_args_from_request() );

		return add_query_arg( $args, admin_url( 'admin.php' ) );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $section_id Section id.
	 */
	public function settings_section_url( $section_id ) {
		return $this->tab_url( 'settings' ) . '#noesia-cs-settings-' . sanitize_key( $section_id );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $order_id Order id.
	 */
	public function printable_qr_url( $order_id ) {
		$order_id = absint( $order_id );
		if ( ! $order_id ) {
			return '';
		}
		return wp_nonce_url(
			admin_url( 'admin-post.php?action=noesia_cs_print_qr&order_id=' . $order_id ),
			'noesia_cs_print_qr_' . $order_id
		);
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $message Message.
	 */
	public function empty_panel( $message ) {
		?>
		<div class="noesia-cs-panel"><p><?php echo esc_html( $message ); ?></p></div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $title Title.
	 * @param mixed $value Value.
	 * @param mixed $trend_icon Trend icon.
	 * @param mixed $trend Trend.
	 * @param mixed $icon Icon.
	 */
	public function metric_card( $title, $value, $trend_icon, $trend, $icon ) {
		?>
		<article class="noesia-cs-metric">
			<div>
				<span><?php echo esc_html( $title ); ?></span>
				<strong><?php echo esc_html( $value ); ?></strong>
				<em><?php echo esc_html( $trend_icon . ' ' . $trend ); ?></em>
			</div>
			<i class="noesia-cs-metric__icon is-<?php echo esc_attr( $icon ); ?>">●</i>
		</article>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $stats Stats.
	 * @param mixed $display_value Display value.
	 * @param mixed $range_label Range label.
	 */
	public function revenue_metric_card( $stats, $display_value, $range_label ) {
		$revenue  = isset( $stats['total_revenue'] ) ? (float) $stats['total_revenue'] : 0.0;
		$start    = isset( $stats['range_start_ts'] ) ? absint( $stats['range_start_ts'] ) : 0;
		$end      = isset( $stats['range_end_ts'] ) ? absint( $stats['range_end_ts'] ) : time();
		$seconds  = max( 1, $end - $start );
		$rates   = array(
			__( 'Per second', 'noesia-commerce-suite' )         => $revenue / $seconds,
			__( 'Per minute', 'noesia-commerce-suite' )         => ( $revenue / $seconds ) * MINUTE_IN_SECONDS,
			__( 'Per hour', 'noesia-commerce-suite' )           => ( $revenue / $seconds ) * HOUR_IN_SECONDS,
			__( 'Per 24 hours', 'noesia-commerce-suite' )       => ( $revenue / $seconds ) * DAY_IN_SECONDS,
			__( 'Projected 30 days', 'noesia-commerce-suite' )  => ( $revenue / $seconds ) * 30 * DAY_IN_SECONDS,
		);
		$format_money = function ( $amount ) {
			return function_exists( 'wc_price' ) ? wp_strip_all_tags( wc_price( $amount ) ) : number_format_i18n( (float) $amount, 2 );
		};
		?>
		<article class="noesia-cs-metric noesia-cs-metric--revenue">
			<div><span><?php esc_html_e( 'Total Revenue', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( $display_value ); ?></strong><em><?php echo esc_html( '● ' . $range_label ); ?></em></div>
			<button type="button" class="noesia-cs-metric__icon noesia-cs-metric__action is-currency" data-noesia-cs-open-modal="#noesia-cs-revenue-velocity-modal" aria-label="<?php esc_attr_e( 'Open revenue pace analysis', 'noesia-commerce-suite' ); ?>">$</button>
		</article>
		<div class="noesia-cs-modal" id="noesia-cs-revenue-velocity-modal" hidden role="dialog" aria-modal="true" aria-labelledby="noesia-cs-revenue-velocity-title">
			<div class="noesia-cs-modal__backdrop" data-noesia-cs-close-modal="1"></div>
			<div class="noesia-cs-modal__panel">
				<button type="button" class="noesia-cs-modal__close" data-noesia-cs-close-modal="1" aria-label="<?php esc_attr_e( 'Close', 'noesia-commerce-suite' ); ?>">×</button>
				<span class="noesia-cs-modal__eyebrow"><?php echo esc_html( $range_label ); ?></span>
				<h2 id="noesia-cs-revenue-velocity-title"><?php esc_html_e( 'Revenue Pace', 'noesia-commerce-suite' ); ?></h2>
				<p><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Breakdown of the selected revenue amount: %s.', 'noesia-commerce-suite' ), esc_html( $display_value ) ); ?></p>
				<div class="noesia-cs-velocity-grid">
					<?php foreach ( $rates as $label => $amount ) : ?>
						<div><span><?php echo esc_html( $label ); ?></span><strong><?php echo esc_html( $format_money( $amount ) ); ?></strong></div>
					<?php endforeach; ?>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $skin Skin.
	 * @param mixed $title Title.
	 * @param mixed $text Text.
	 * @param mixed $value Value.
	 * @param mixed $label Label.
	 * @param mixed $tab Tab.
	 * @param mixed $prompt Prompt.
	 */
	public function module_panel( $skin, $title, $text, $value, $label, $tab, $prompt = '' ) {
		?>
		<div class="noesia-cs-panel noesia-cs-module noesia-cs-module--<?php echo esc_attr( $skin ); ?>">
			<div class="noesia-cs-module__title">
				<h2><?php echo esc_html( $title ); ?></h2>
				<a href="<?php echo esc_url( $this->tab_url( $tab ) ); ?>"><?php esc_html_e( 'View', 'noesia-commerce-suite' ); ?></a>
			</div>
			<p><?php echo esc_html( $text ); ?></p>
			<?php if ( $prompt ) : ?>
				<p class="noesia-cs-module__prompt"><?php echo esc_html( $prompt ); ?></p>
			<?php endif; ?>
			<div class="noesia-cs-module__stat">
				<strong><?php echo esc_html( $value ); ?></strong>
				<span><?php echo esc_html( $label ); ?></span>
			</div>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $title Title.
	 * @param mixed $description Description.
	 * @param mixed $feature Feature.
	 */
	public function pro_edition_card( $title, $description, $feature = '' ) {
		$feature  = sanitize_key( $feature );
		$active   = $feature ? $this->feature_service->can_use( $feature ) : $this->feature_service->is_pro_active();
		$url      = $this->feature_service->get_upgrade_url();
		?>
		<div class="noesia-cs-pro-edition-card <?php echo $active ? 'is-available' : 'is-explore'; ?>"<?php echo $feature ? ' data-noesia-cs-feature="' . esc_attr( $feature ) . '"' : ''; ?>>
			<span><?php echo esc_html( $active ? __( 'Pro Edition', 'noesia-commerce-suite' ) : __( 'Separate Pro Edition', 'noesia-commerce-suite' ) ); ?></span>
			<h3><?php echo esc_html( $title ); ?></h3>
			<p><?php echo esc_html( $description ); ?></p>
			<?php if ( $active ) : ?>
				<em><?php esc_html_e( 'Included in your active Pro Edition.', 'noesia-commerce-suite' ); ?></em>
			<?php else : ?>
				<a href="<?php echo esc_url( $url ); ?>"><?php esc_html_e( 'Explore Pro Edition', 'noesia-commerce-suite' ); ?></a>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $series Series.
	 */
	public function render_revenue_svg( $series ) {
		$series  = is_array( $series ) ? $series : array();
		$values  = array_map( 'floatval', array_values( $series ) );
		$labels  = array_map( 'sanitize_text_field', array_keys( $series ) );
		$max     = max( 1, max( $values ? $values : array( 1 ) ) );
		$points  = array();
		$nodes   = array();
		$count   = max( 1, count( $values ) - 1 );

		foreach ( $values as $i => $value ) {
			$x  = round( ( $i / $count ) * 1000, 2 );
			$y  = round( 220 - ( $value / $max ) * 170, 2 );
			$points[] = $x . ',' . $y;
			$money    = function_exists( 'wc_price' ) ? wp_strip_all_tags( wc_price( $value ) ) : number_format_i18n( $value, 2 );
			$nodes[]  = array(
				'x'      => $x,
				'y'      => $y,
				'label'  => isset( $labels[ $i ] ) ? $labels[ $i ] : '',
				'value'  => $money,
			);
		}

		if ( empty( $points ) ) {
			$points[] = '0,220';
		}
		?>
		<div class="noesia-cs-chart">
			<svg viewBox="0 0 1000 260" preserveAspectRatio="none" role="img" aria-label="<?php esc_attr_e( 'Revenue chart', 'noesia-commerce-suite' ); ?>">
				<defs><linearGradient id="noesiaCsLineFill" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="var(--noesia-cs-primary)" stop-opacity=".22"/><stop offset="1" stop-color="var(--noesia-cs-primary)" stop-opacity="0"/></linearGradient></defs>
				<g class="grid">
					<?php for ( $i = 0; $i < 5; ++$i ) : ?>
						<line x1="0" y1="<?php echo esc_attr( 40 + $i * 45 ); ?>" x2="1000" y2="<?php echo esc_attr( 40 + $i * 45 ); ?>"/>
					<?php endfor; ?>
				</g>
				<polygon points="0,230 <?php echo esc_attr( implode( ' ', $points ) ); ?> 1000,230" fill="url(#noesiaCsLineFill)"/>
				<polyline points="<?php echo esc_attr( implode( ' ', $points ) ); ?>" fill="none" stroke="var(--noesia-cs-primary)" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
				<?php foreach ( $nodes as $node ) : ?>
					<g class="noesia-cs-chart-point" tabindex="0" aria-label="<?php echo esc_attr( trim( $node['label'] . ' ' . $node['value'] ) ); ?>">
						<circle cx="<?php echo esc_attr( $node['x'] ); ?>" cy="<?php echo esc_attr( $node['y'] ); ?>" r="9"></circle>
						<text x="<?php echo esc_attr( $node['x'] ); ?>" y="<?php echo esc_attr( max( 20, $node['y'] - 18 ) ); ?>"><?php echo esc_html( $node['value'] ); ?></text>
						<title><?php echo esc_html( trim( $node['label'] . ': ' . $node['value'] ) ); ?></title>
					</g>
				<?php endforeach; ?>
			</svg>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $stats Stats.
	 */
	public function render_order_health( $stats ) {
		$status_counts  = isset( $stats['orders_by_status'] ) && is_array( $stats['orders_by_status'] ) ? $stats['orders_by_status'] : array();
		$total_count    = array_sum( array_map( 'absint', $status_counts ) );
		$percent_base   = max( 1, $total_count );
		$colors         = array( '#ef4444', '#8b5cf6', '#f59e0b', '#22c55e', '#3b82f6', '#14b8a6', '#ec4899', '#64748b' );
		$segments       = array();
		$cursor         = 0;
		$index          = 0;

		foreach ( $status_counts as $status => $count ) {
			$count = absint( $count );
			if ( 0 === $count ) {
				continue;
			}
			$percent  = ( $count / $percent_base ) * 100;
			$color    = $colors[ $index % count( $colors ) ];
			$start    = $cursor;
			$cursor += $percent;
			$segments[] = array(
				'color'    => $color,
				'start'    => $start,
				'end'      => min( 100, $cursor ),
				'status'   => $status,
				'count'    => $count,
				'percent'  => $percent,
			);
			++$index;
		}

		$gradient_parts = array();
		foreach ( $segments as $segment ) {
			$gradient_parts[] = sprintf( '%1$s %2$.2f%% %3$.2f%%', $segment['color'], $segment['start'], $segment['end'] );
		}
		$donut_style = $gradient_parts ? 'background:conic-gradient(' . implode( ',', $gradient_parts ) . ');' : '';
		?>
		<div class="noesia-cs-health">
			<div class="noesia-cs-donut" style="<?php echo esc_attr( $donut_style ); ?>">
				<div class="noesia-cs-donut__center">
					<strong><?php echo esc_html( number_format_i18n( absint( $stats['total_orders'] ?? 0 ) ) ); ?></strong>
					<span><?php esc_html_e( 'Total Orders', 'noesia-commerce-suite' ); ?></span>
				</div>
			</div>
			<div class="noesia-cs-health__list">
				<?php foreach ( $segments as $segment ) : ?>
					<div>
						<span><i class="noesia-cs-health__legend-dot" style="--noesia-cs-status-color:<?php echo esc_attr( $segment['color'] ); ?>"></i><?php echo esc_html( function_exists( 'wc_get_order_status_name' ) ? wc_get_order_status_name( $segment['status'] ) : $segment['status'] ); ?></span>
						<strong><?php echo esc_html( number_format_i18n( absint( $segment['count'] ) ) ); ?> <small><?php echo esc_html( round( $segment['percent'], 1 ) ); ?>%</small></strong>
					</div>
				<?php endforeach; ?>
				<?php if ( empty( $segments ) ) : ?>

					<p><?php esc_html_e( 'No orders found in the selected range.', 'noesia-commerce-suite' ); ?></p>

				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $summary Summary.
	 * @param mixed $range_label Range label.
	 */
	public function render_support_preview( $summary = array(), $range_label = '' ) {
		$support  = absint( $summary['support'] ?? 0 );
		$review   = absint( $summary['review'] ?? 0 );
		$total    = absint( $summary['range_count'] ?? ( $support + $review ) );
		?>
		<div class="noesia-cs-care-activity-preview">
			<?php if ( $range_label ) : ?>

				<p class="noesia-cs-care-activity-preview__note"><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Tracked customer care button clicks for %s.', 'noesia-commerce-suite' ), esc_html( $range_label ) ); ?></p>

			<?php endif; ?>
			<div class="noesia-cs-care-activity-preview__row"><span><?php esc_html_e( 'Support button clicks', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( number_format_i18n( $support ) ); ?></strong></div>
			<div class="noesia-cs-care-activity-preview__row"><span><?php esc_html_e( 'Review button clicks', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( number_format_i18n( $review ) ); ?></strong></div>
			<div class="noesia-cs-care-activity-preview__total"><span><?php esc_html_e( 'Total care page clicks', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( number_format_i18n( $total ) ); ?></strong></div>
			<?php if ( 0 === $total ) : ?>
				<p><?php esc_html_e( 'Counts change only after customers click support, review or reorder buttons inside Order Care Hub links.', 'noesia-commerce-suite' ); ?></p>
			<?php endif; ?>
		</div>
		<?php
	}
	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $items Items.
	 */
	public function render_top_products( $items ) {
		$items  = is_array( $items ) ? array_slice( $items, 0, 5 ) : array();
		$max    = 0;
		foreach ( $items as $data ) {
			$max = max( $max, absint( $data['quantity'] ?? 0 ) );
		}
		$max = max( 1, $max );
		?>
		<div class="noesia-cs-bars noesia-cs-bars--products">
			<?php foreach ( $items as $label => $data ) : ?>
				<?php $quantity = absint( $data['quantity'] ?? 0 ); $width = max( 8, ( $quantity / $max ) * 100 ); ?>
				<div class="noesia-cs-bar-row" data-noesia-cs-width="<?php echo esc_attr( $width ); ?>">
					<span><?php echo esc_html( isset( $data['label'] ) ? $data['label'] : $label ); ?></span>
					<strong><?php echo esc_html( number_format_i18n( $quantity ) ); ?> <?php esc_html_e( 'sold', 'noesia-commerce-suite' ); ?></strong>
					<i></i>
				</div>
			<?php endforeach; ?>
			<?php if ( empty( $items ) ) : ?>

				<p><?php esc_html_e( 'No product data in the selected range.', 'noesia-commerce-suite' ); ?></p>

			<?php endif; ?>
		</div>
		<?php
	}


	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $items Items.
	 * @param mixed $active_range Active range.
	 * @param mixed $tab Tab.
	 */
	public function render_dashboard_top_products( $items, $active_range = 'all', $tab = 'dashboard' ) {
		$items         = is_array( $items ) ? array_slice( $items, 0, 10 ) : array();
		$active_range  = in_array( sanitize_key( $active_range ), array( 'all', 'last_month', 'last_24h' ), true ) ? sanitize_key( $active_range ) : 'all';
		$ranges       = array(
			'all'         => __( 'All time', 'noesia-commerce-suite' ),
			'last_month'  => __( 'Last month', 'noesia-commerce-suite' ),
			'last_24h'    => __( 'Last 24h', 'noesia-commerce-suite' ),
		);
		$tab          = in_array( sanitize_key( $tab ), array( 'dashboard', 'intelligence-analytics' ), true ) ? sanitize_key( $tab ) : 'dashboard';
		$format_money = function ( $amount ) {
			return function_exists( 'wc_price' ) ? wp_strip_all_tags( wc_price( $amount ) ) : number_format_i18n( (float) $amount, 2 );
		};
		?>
		<div class="noesia-cs-dashboard-products" data-noesia-cs-dashboard-products="1" data-noesia-cs-dashboard-products-tab="<?php echo esc_attr( $tab ); ?>">
			<div class="noesia-cs-dashboard-products__filters" aria-label="<?php esc_attr_e( 'Top products range', 'noesia-commerce-suite' ); ?>">
				<?php foreach ( $ranges as $range_key => $range_label ) : ?>
					<a class="<?php echo $active_range === $range_key ? 'is-active' : ''; ?>" data-noesia-cs-dashboard-product-range="<?php echo esc_attr( $range_key ); ?>" href="<?php echo esc_url( $this->dashboard_product_range_url( $range_key, $tab ) ); ?>"><?php echo esc_html( $range_label ); ?></a>
				<?php endforeach; ?>
			</div>
			<div class="noesia-cs-dashboard-products__list">
				<?php foreach ( $items as $index => $item ) : ?>
					<?php
					$label      = sanitize_text_field( $item['label'] ?? __( 'Product', 'noesia-commerce-suite' ) );
					$quantity   = absint( $item['quantity'] ?? 0 );
					$revenue    = (float) ( $item['revenue'] ?? 0 );
					$thumb      = esc_url( $item['thumbnail'] ?? '' );
					$url        = esc_url( $item['url'] ?? '' );
					$row_title  = $url ? '<a href="' . $url . '">' . esc_html( $label ) . '</a>' : esc_html( $label );
					?>
					<div class="noesia-cs-dashboard-product-row">
						<span class="noesia-cs-dashboard-product-row__rank"><?php echo esc_html( (string) ( $index + 1 ) ); ?></span>
						<span class="noesia-cs-dashboard-product-row__thumb">
							<?php if ( $thumb ) : ?>
								<img src="<?php echo esc_url( $thumb ); ?>" alt="">
							<?php else : ?>
								<i>◆</i>
							<?php endif; ?>
						</span>
						<span class="noesia-cs-dashboard-product-row__meta"><strong><?php echo wp_kses_post( $row_title ); ?></strong><small><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Sold %s', 'noesia-commerce-suite' ), esc_html( number_format_i18n( $quantity ) ) ); ?></small></span>
						<span class="noesia-cs-dashboard-product-row__revenue"><?php echo esc_html( $format_money( $revenue ) ); ?></span>
					</div>
				<?php endforeach; ?>
				<?php if ( empty( $items ) ) : ?>

					<p><?php esc_html_e( 'No sold product data found for this range yet.', 'noesia-commerce-suite' ); ?></p>

				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $orders Orders.
	 */
	public function render_recent_orders_preview( $orders ) {
		$orders = is_array( $orders ) ? array_slice( $orders, 0, 5 ) : array();
		$format_money = function ( $amount ) {
			return function_exists( 'wc_price' ) ? wp_strip_all_tags( wc_price( $amount ) ) : number_format_i18n( (float) $amount, 2 );
		};
		?>
		<div class="noesia-cs-recent-orders-preview">
			<?php foreach ( $orders as $order ) : ?>
				<?php
				$order_number  = sanitize_text_field( $order['order_number'] ?? '' );
				$status        = sanitize_key( $order['status'] ?? '' );
				$status_label  = sanitize_text_field( $order['status_label'] ?? $status );
				$thumb         = esc_url( $order['thumbnail'] ?? '' );
				$url           = esc_url( $order['url'] ?? '' );
				?>
				<div class="noesia-cs-recent-order-row">
					<strong class="noesia-cs-recent-order-row__number"><?php echo esc_html( '#' . $order_number ); ?></strong>
					<span class="noesia-cs-recent-order-row__thumb">
						<?php if ( $thumb ) : ?>
							<img src="<?php echo esc_url( $thumb ); ?>" alt="">
						<?php else : ?>
							<i>◆</i>
						<?php endif; ?>
					</span>
					<span class="noesia-cs-recent-order-row__customer"><?php echo wp_kses_post( $url ? '<a href="' . esc_url( $url ) . '">' . esc_html( $order['customer_label'] ?? __( 'Customer', 'noesia-commerce-suite' ) ) . '</a>' : esc_html( $order['customer_label'] ?? __( 'Customer', 'noesia-commerce-suite' ) ) ); ?></span>
					<span class="noesia-cs-recent-order-row__amount"><?php echo esc_html( $format_money( $order['total'] ?? 0 ) ); ?></span>
					<span class="noesia-cs-recent-order-row__status is-<?php echo esc_attr( $status ); ?>"><?php echo esc_html( $status_label ); ?></span>
					<em><?php echo esc_html( $order['time_ago'] ?? '' ); ?></em>
				</div>
			<?php endforeach; ?>
			<?php if ( empty( $orders ) ) : ?>

				<p><?php esc_html_e( 'No recent WooCommerce orders found yet.', 'noesia-commerce-suite' ); ?></p>

			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $stats Stats.
	 */
	public function render_dashboard_order_health( $stats ) {
		$status_counts  = isset( $stats['orders_by_status'] ) && is_array( $stats['orders_by_status'] ) ? $stats['orders_by_status'] : array();
		$total          = max( 0, absint( $stats['total_orders'] ?? array_sum( array_map( 'absint', $status_counts ) ) ) );
		$completed      = absint( $status_counts['completed'] ?? 0 );
		$cancelled      = absint( $status_counts['cancelled'] ?? 0 );
		$refunded       = absint( $status_counts['refunded'] ?? 0 );
		$failed         = absint( $status_counts['failed'] ?? 0 );
		$success_count  = max( 0, $total - $cancelled - $refunded - $failed );

		$completion_rate    = $total ? ( $completed / $total ) * 100 : 0;
		$success_rate       = $total ? ( $success_count / $total ) * 100 : 0;
		$cancellation_rate  = $total ? ( $cancelled / $total ) * 100 : 0;
		$refund_rate        = $total ? ( $refunded / $total ) * 100 : 0;
		$score              = $total ? ( $completion_rate * .35 ) + ( $success_rate * .45 ) + ( ( 100 - $cancellation_rate ) * .10 ) + ( ( 100 - $refund_rate ) * .10 ) : 0;
		$score              = max( 0, min( 100, round( $score ) ) );
		$arc_length         = 251.33;
		$dash               = round( ( $score / 100 ) * $arc_length, 2 );
		$label              = __( 'Needs Attention', 'noesia-commerce-suite' );
		if ( $score >= 90 ) {
			$label = __( 'Excellent', 'noesia-commerce-suite' );
		} elseif ( $score >= 75 ) {
			$label = __( 'Good', 'noesia-commerce-suite' );
		} elseif ( $score >= 60 ) {
			$label = __( 'Fair', 'noesia-commerce-suite' );
		} elseif ( ! $total ) {
			$label = __( 'No orders yet', 'noesia-commerce-suite' );
		}

		$metrics = array(
			array(
				'label'  => __( 'Completion Rate', 'noesia-commerce-suite' ),
				'value'  => $completion_rate,
				'class'  => 'completion',
				'help'   => __( 'Completed orders divided by total orders in this range.', 'noesia-commerce-suite' ),
			),
			array(
				'label'  => __( 'Success Rate', 'noesia-commerce-suite' ),
				'value'  => $success_rate,
				'class'  => 'success',
				'help'   => __( 'Orders not cancelled, refunded or failed divided by total orders in this range.', 'noesia-commerce-suite' ),
			),
			array(
				'label'  => __( 'Cancellation Rate', 'noesia-commerce-suite' ),
				'value'  => $cancellation_rate,
				'class'  => 'cancellation',
				'help'   => __( 'Cancelled orders divided by total orders in this range.', 'noesia-commerce-suite' ),
			),
			array(
				'label'  => __( 'Refund Rate', 'noesia-commerce-suite' ),
				'value'  => $refund_rate,
				'class'  => 'refund',
				'help'   => __( 'Refunded orders divided by total orders in this range.', 'noesia-commerce-suite' ),
			),
		);
		?>
		<div class="noesia-cs-order-health-card">
			<div class="noesia-cs-order-health-card__gauge" aria-label="<?php echo esc_attr( sprintf( /* translators: %d: numeric value. */ __( 'Order health score %d out of 100', 'noesia-commerce-suite' ), $score ) ); ?>">
				<svg viewBox="0 0 220 132" role="img" focusable="false">
					<defs><linearGradient id="noesiaCsOrderHealthGradient" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stop-color="#ef4444"/><stop offset=".45" stop-color="#f59e0b"/><stop offset=".72" stop-color="#8b5cf6"/><stop offset="1" stop-color="#22c55e"/></linearGradient></defs>
					<path d="M30 110 A80 80 0 0 1 190 110" pathLength="251.33" class="noesia-cs-order-health-card__track"></path>
					<path d="M30 110 A80 80 0 0 1 190 110" pathLength="251.33" class="noesia-cs-order-health-card__value" style="stroke-dasharray:<?php echo esc_attr( $dash ); ?> 251.33"></path>
				</svg>
				<div class="noesia-cs-order-health-card__score"><strong><?php echo esc_html( number_format_i18n( $score ) ); ?></strong><span><?php echo esc_html( $label ); ?></span></div>
			</div>
			<div class="noesia-cs-order-health-card__metrics">
				<?php foreach ( $metrics as $metric ) : ?>
					<div class="is-<?php echo esc_attr( $metric['class'] ); ?>" title="<?php echo esc_attr( $metric['help'] ); ?>">
						<span><i></i><?php echo esc_html( $metric['label'] ); ?></span>
						<strong><?php echo esc_html( number_format_i18n( round( $metric['value'], 1 ), 1 ) ); ?>%</strong>
					</div>
				<?php endforeach; ?>
				<p><?php esc_html_e( 'Completion Rate counts completed WooCommerce orders. Success Rate counts orders that are not cancelled, refunded or failed.', 'noesia-commerce-suite' ); ?></p>
			</div>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $summary Summary.
	 * @param mixed $range_label Range label.
	 */
	public function render_customer_retention( $summary, $range_label = '' ) {
		$summary             = is_array( $summary ) ? $summary : array();
		$available           = ! empty( $summary['available'] );
		$unique              = absint( $summary['unique_customers'] ?? 0 );
		$new                 = absint( $summary['new_customers'] ?? 0 );
		$returning           = absint( $summary['returning_customers'] ?? 0 );
		$repeat_rate         = (float) ( $summary['repeat_purchase_rate'] ?? 0 );
		$average_orders      = (float) ( $summary['average_orders_per_customer'] ?? 0 );
		$reorder_candidates  = absint( $summary['reorder_candidates'] ?? 0 );
		$range_label         = $range_label ? $range_label : sanitize_text_field( $summary['range_label'] ?? '' );
		?>
		<div class="noesia-cs-customer-retention-card">
			<?php if ( ! $available ) : ?>
				<div class="noesia-cs-customer-retention-card__empty">
					<strong><?php esc_html_e( 'Customer retention data is not available yet.', 'noesia-commerce-suite' ); ?></strong>
					<p><?php esc_html_e( 'The panel will show values after WooCommerce customer/order lookup data is available.', 'noesia-commerce-suite' ); ?></p>
				</div>
			<?php else : ?>
				<div class="noesia-cs-customer-retention-card__hero">
					<span><?php esc_html_e( 'Returning Customers', 'noesia-commerce-suite' ); ?></span>
					<strong><?php echo esc_html( number_format_i18n( round( (float) ( $summary['returning_customer_rate'] ?? 0 ), 1 ), 1 ) ); ?>%</strong>
					<small><?php printf( /* translators: 1: first dynamic value; 2: second dynamic value. */ esc_html__( '%1$s of %2$s customers', 'noesia-commerce-suite' ), esc_html( number_format_i18n( $returning ) ), esc_html( number_format_i18n( $unique ) ) ); ?></small>
				</div>
				<div class="noesia-cs-customer-retention-card__grid">
					<div><span><?php esc_html_e( 'New Customers', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( number_format_i18n( $new ) ); ?></strong></div>
					<div><span><?php esc_html_e( 'Repeat Purchase Rate', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( number_format_i18n( round( $repeat_rate, 1 ), 1 ) ); ?>%</strong></div>
					<div><span><?php esc_html_e( 'Avg. Orders / Customer', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( number_format_i18n( round( $average_orders, 2 ), 2 ) ); ?></strong></div>
					<div><span><?php esc_html_e( 'Reorder Candidates', 'noesia-commerce-suite' ); ?></span><strong><?php echo esc_html( number_format_i18n( $reorder_candidates ) ); ?></strong></div>
				</div>
				<p><?php esc_html_e( 'New/returning/repeat values use WooCommerce customer lookup records and valid commerce orders. Reorder candidates are unique customers with pending reorder reminders.', 'noesia-commerce-suite' ); ?><?php if ( $range_label ) : ?> <?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Range: %s.', 'noesia-commerce-suite' ), esc_html( $range_label ) ); ?><?php endif; ?></p>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $range Range.
	 * @param mixed $tab Tab.
	 */
	private function dashboard_product_range_url( $range, $tab = 'dashboard' ) {
		$tab  = sanitize_key( $tab );
		$tab  = $tab ? $tab : 'dashboard';
		$args = array(
			'page'                       => 'noesia-commerce-suite',
			'tab'                        => $tab,
			'noesia_cs_product_range'    => sanitize_key( $range ),
			'noesia_cs_dashboard_nonce'  => wp_create_nonce( 'noesia_cs_dashboard_range' ),
		);

		$args = array_merge( $args, $this->dashboard_date_query_args_from_request() );

		return add_query_arg( $args, admin_url( 'admin.php' ) );
	}

	/**
	 * Returns verified dashboard date query arguments from the current admin request.
	 */
	private function dashboard_date_query_args_from_request() {
		if ( ! $this->has_valid_dashboard_range_request() ) {
			return array();
		}

		$args = array(
			'noesia_cs_dashboard_nonce'  => wp_create_nonce( 'noesia_cs_dashboard_range' ),
		);

		$date_keys = array( 'noesia_cs_date_mode', 'noesia_cs_date_from', 'noesia_cs_date_to' );
		foreach ( $date_keys as $date_key ) {
			if ( isset( $_GET[ $date_key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Verified by has_valid_dashboard_range_request().
				$args[ $date_key ] = sanitize_text_field( wp_unslash( $_GET[ $date_key ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Verified by has_valid_dashboard_range_request().
			}
		}

		return $args;
	}

	/**
	 * Checks whether dashboard range query arguments came from a valid admin request.
	 */
	private function has_valid_dashboard_range_request() {
		if ( ! current_user_can( NOESIA_CS_CAPABILITY ) ) {
			return false;
		}

		if ( empty( $_GET['noesia_cs_dashboard_nonce'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The nonce is verified below when present.
			return false;
		}

		$nonce = sanitize_text_field( wp_unslash( $_GET['noesia_cs_dashboard_nonce'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The nonce is verified on the next line.

		return (bool) wp_verify_nonce( $nonce, 'noesia_cs_dashboard_range' );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $snapshot Snapshot.
	 * @param mixed $display_group_by Display group by.
	 */
	public function render_map_preview( $snapshot, $display_group_by = '' ) {
		$display_group_by  = $display_group_by ? sanitize_key( $display_group_by ) : sanitize_key( Noesia_CS_Settings::get( 'impact_map_group_by', 'country' ) );
		$display_group_by  = in_array( $display_group_by, array( 'city', 'region', 'country' ), true ) ? $display_group_by : 'country';
		$areas             = $this->prepare_impact_areas_for_display( $snapshot, $display_group_by, 6 );
		$group_label       = $this->impact_group_label( $display_group_by );
		?>
		<div class="noesia-cs-impact-compact">
			<div class="noesia-cs-impact-compact__title">
				<span><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Showing by %s', 'noesia-commerce-suite' ), esc_html( $group_label ) ); ?></span>
				<a href="<?php echo esc_url( $this->tab_url( 'impact-map' ) ); ?>"><?php esc_html_e( 'Manage map', 'noesia-commerce-suite' ); ?></a>
			</div>
			<?php if ( ! empty( $areas ) ) : ?>
				<div class="noesia-cs-impact-compact__head"><span><?php echo esc_html( $group_label ); ?></span><span><?php esc_html_e( 'Orders', 'noesia-commerce-suite' ); ?></span></div>
				<?php foreach ( $areas as $area ) : ?>
					<div class="noesia-cs-impact-row">
						<strong><span class="noesia-cs-flag"><?php echo esc_html( $this->country_flag( $area['country'] ?? '' ) ); ?></span><?php echo esc_html( $this->area_display_label( $area ) ); ?></strong>
						<span><?php echo esc_html( number_format_i18n( absint( $area['orders'] ?? 0 ) ) ); ?></span>
					</div>
				<?php endforeach; ?>
			<?php else : ?>
				<p><?php esc_html_e( 'No cached impact areas yet. Refresh the Impact Map snapshot after Woo orders exist.', 'noesia-commerce-suite' ); ?></p>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $snapshot Snapshot.
	 * @param mixed $display_group_by Display group by.
	 */
	public function render_impact_admin_table( $snapshot, $display_group_by = 'country' ) {
		$display_group_by  = in_array( sanitize_key( $display_group_by ), array( 'city', 'region', 'country' ), true ) ? sanitize_key( $display_group_by ) : 'country';
		$group_label       = $this->impact_group_label( $display_group_by );
		$areas             = $this->prepare_impact_areas_for_display( $snapshot, $display_group_by, 10 );
		?>
		<div class="noesia-cs-impact-admin-preview" data-noesia-cs-impact-preview="admin-table">
			<?php if ( empty( $snapshot['generated_at'] ) ) : ?>
				<p><?php esc_html_e( 'No Impact Map snapshot has been generated yet. Choose the grouping and click Refresh Snapshot to build the first privacy-safe public snapshot.', 'noesia-commerce-suite' ); ?></p>
			<?php else : ?>
				<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Showing the top 10 public areas to keep the admin view readable. The public shortcode uses the same cached privacy-safe snapshot.', 'noesia-commerce-suite' ); ?><?php if ( ! empty( $snapshot['hidden_areas_count'] ) ) : ?> <?php printf( /* translators: %d: numeric value. */ esc_html__( '%d low-volume areas are hidden publicly by the privacy threshold.', 'noesia-commerce-suite' ), absint( $snapshot['hidden_areas_count'] ) ); ?><?php endif; ?></p>
				<div class="noesia-cs-table-wrap"><table class="noesia-cs-table noesia-cs-impact-admin-table"><thead><tr><th><?php echo esc_html( $group_label ); ?></th><th><?php esc_html_e( 'Orders', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Products', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Top Categories', 'noesia-commerce-suite' ); ?></th><th><?php esc_html_e( 'Top Products', 'noesia-commerce-suite' ); ?></th></tr></thead><tbody>
				<?php foreach ( $areas as $area ) : ?>
					<tr><td><strong><span class="noesia-cs-flag"><?php echo esc_html( $this->country_flag( $area['country'] ?? '' ) ); ?></span><?php echo esc_html( $this->area_display_label( $area ) ); ?></strong></td><td><?php echo esc_html( number_format_i18n( $area['orders'] ) ); ?></td><td><?php echo esc_html( number_format_i18n( $area['products'] ) ); ?></td><td><?php echo esc_html( implode( ', ', array_map( 'sanitize_text_field', $area['top_categories'] ) ) ); ?></td><td><?php echo esc_html( implode( ', ', array_map( 'sanitize_text_field', $area['top_products'] ) ) ); ?></td></tr>
				<?php endforeach; ?>
				<?php if ( empty( $areas ) ) : ?>

					<tr><td colspan="5"><?php esc_html_e( 'No areas meet the configured privacy threshold.', 'noesia-commerce-suite' ); ?></td></tr>

				<?php endif; ?>
				</tbody></table></div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $snapshot Snapshot.
	 * @param mixed $display_group_by Display group by.
	 * @param mixed $limit Limit.
	 */
	public function prepare_impact_areas_for_display( $snapshot, $display_group_by = 'country', $limit = 10 ) {
		$source            = isset( $snapshot['areas'] ) && is_array( $snapshot['areas'] ) ? $snapshot['areas'] : array();
		$display_group_by  = in_array( sanitize_key( $display_group_by ), array( 'city', 'region', 'country' ), true ) ? sanitize_key( $display_group_by ) : 'country';
		$grouped           = array();

		foreach ( $source as $area ) {
			$country        = sanitize_text_field( $area['country'] ?? '' );
			$country_label  = sanitize_text_field( $area['country_label'] ?? $country );
			$region         = sanitize_text_field( $area['region'] ?? '' );
			$city           = sanitize_text_field( $area['city'] ?? '' );

			if ( 'country' === $display_group_by ) {
				$key    = 'country|' . $country_label;
				$label  = $country_label;
			} elseif ( 'region' === $display_group_by ) {
				$key    = 'region|' . $region . '|' . $country_label;
				$label  = implode( ', ', array_filter( array( $region, $country_label ) ) );
			} else {
				$key    = 'city|' . $city . '|' . $country_label;
				$label  = implode( ', ', array_filter( array( $city, $country_label ) ) );
			}

			if ( ! $label ) {
				$label = sanitize_text_field( $area['label'] ?? '' );
			}
			if ( ! $label ) {
				continue;
			}

			if ( ! isset( $grouped[ $key ] ) ) {
				$grouped[ $key ] = array(
					'label'           => $label,
					'city'            => 'city' === $display_group_by ? $city : '',
					'region'          => 'region' === $display_group_by ? $region : '',
					'country'         => $country,
					'country_label'   => $country_label,
					'group_by'        => $display_group_by,
					'orders'          => 0,
					'products'        => 0,
					'revenue'         => 0,
					'top_categories'  => array(),
					'top_products'    => array(),
				);
			}

			$grouped[ $key ]['orders']   += absint( $area['orders'] ?? 0 );
			$grouped[ $key ]['products'] += absint( $area['products'] ?? 0 );
			$grouped[ $key ]['revenue']  += (float) ( $area['revenue'] ?? 0 );
			$grouped[ $key ]['top_categories'] = array_values( array_unique( array_merge( $grouped[ $key ]['top_categories'], array_map( 'sanitize_text_field', $area['top_categories'] ?? array() ) ) ) );
			$grouped[ $key ]['top_products']   = array_values( array_unique( array_merge( $grouped[ $key ]['top_products'], array_map( 'sanitize_text_field', $area['top_products'] ?? array() ) ) ) );
		}

		uasort(
			$grouped,
			function ( $a, $b ) {
				return ( absint( $b['orders'] ) <=> absint( $a['orders'] ) );
			}
		);

		$rows = array_values( $grouped );
		return array_slice( $rows, 0, max( 1, absint( $limit ) ) );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $group_by Group by.
	 */
	public function impact_group_label( $group_by ) {
		$labels = array(
			'city'     => __( 'City', 'noesia-commerce-suite' ),
			'region'   => __( 'Region / State', 'noesia-commerce-suite' ),
			'country'  => __( 'Country', 'noesia-commerce-suite' ),
		);
		$group_by = sanitize_key( $group_by );
		return $labels[ $group_by ] ?? $labels['country'];
	}
	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $payment_methods Payment methods.
	 * @param mixed $range_label Range label.
	 */
	public function render_payment_preview( $payment_methods, $range_label ) {
		$payment_methods = is_array( $payment_methods ) ? array_slice( $payment_methods, 0, 4 ) : array();
		?>
		<div class="noesia-cs-payment-preview">
			<div class="noesia-cs-payment-preview__note"><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Payment methods in selected range: %s', 'noesia-commerce-suite' ), esc_html( $range_label ) ); ?></div>
			<?php foreach ( $payment_methods as $method ) : ?>
				<div class="noesia-cs-payment-row">
					<strong><?php echo esc_html( $method['label'] ?? __( 'Payment method', 'noesia-commerce-suite' ) ); ?></strong>
					<span><?php echo esc_html( number_format_i18n( absint( $method['orders'] ?? 0 ) ) ); ?> <?php esc_html_e( 'orders', 'noesia-commerce-suite' ); ?></span>
				</div>
			<?php endforeach; ?>
			<?php if ( empty( $payment_methods ) ) : ?>

				<p><?php esc_html_e( 'No payment method data in the selected date range.', 'noesia-commerce-suite' ); ?></p>

			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $stats Stats.
	 */
	public function render_dashboard_date_filter( $stats ) {
		$mode = isset( $stats['range_mode'] ) ? sanitize_key( $stats['range_mode'] ) : 'preset';
		?>
		<form class="noesia-cs-date-filter" method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" data-noesia-cs-date-filter="1">
			<?php wp_nonce_field( 'noesia_cs_dashboard_range', 'noesia_cs_dashboard_nonce', false ); ?>
			<input type="hidden" name="page" value="noesia-commerce-suite">
			<input type="hidden" name="tab" value="<?php echo esc_attr( isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'dashboard' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only tab persistence for admin date filter. ?>">
			<label>
				<span><?php esc_html_e( 'Analysis range', 'noesia-commerce-suite' ); ?></span>
				<select name="noesia_cs_date_mode">
					<option value="preset" <?php selected( $mode, 'preset' ); ?>><?php printf( /* translators: %d: numeric value. */ esc_html__( 'Default setting: %d days', 'noesia-commerce-suite' ), absint( $stats['date_range_days'] ?? 30 ) ); ?></option>
					<option value="custom" <?php selected( $mode, 'custom' ); ?>><?php esc_html_e( 'Custom dates', 'noesia-commerce-suite' ); ?></option>
				</select>
			</label>
			<label><span><?php esc_html_e( 'From', 'noesia-commerce-suite' ); ?></span><input type="date" name="noesia_cs_date_from" value="<?php echo esc_attr( $stats['range_start'] ?? '' ); ?>"></label>
			<label><span><?php esc_html_e( 'To', 'noesia-commerce-suite' ); ?></span><input type="date" name="noesia_cs_date_to" value="<?php echo esc_attr( $stats['range_end'] ?? '' ); ?>"></label>
			<button class="noesia-cs-secondary-button" type="submit"><?php esc_html_e( 'Apply', 'noesia-commerce-suite' ); ?></button>
		</form>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $area Area.
	 */
	public function area_display_label( $area ) {
		$group_by  = isset( $area['group_by'] ) ? sanitize_key( $area['group_by'] ) : sanitize_key( Noesia_CS_Settings::get( 'impact_map_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'] ?? '' );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $country_code Country code.
	 */
	public function country_flag( $country_code ) {
		$country_code = preg_replace( '/[^A-Z]/', '', strtoupper( (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;
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $report Report.
	 */
	public function render_doctor_preview( $report ) {
		$items   = isset( $report['items'] ) && is_array( $report['items'] ) ? $report['items'] : array();
		$counts  = isset( $report['severity_counts'] ) && is_array( $report['severity_counts'] ) ? $report['severity_counts'] : array();
		?>
		<div class="noesia-cs-doctor-summary">
			<div><strong><?php echo esc_html( number_format_i18n( absint( $report['scanned_products'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'Products scanned', 'noesia-commerce-suite' ); ?></span></div>
			<div><strong><?php echo esc_html( number_format_i18n( count( $items ) ) ); ?></strong><span><?php esc_html_e( 'Result rows', 'noesia-commerce-suite' ); ?></span></div>
			<div><strong><?php echo esc_html( number_format_i18n( absint( $counts['high'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'High severity', 'noesia-commerce-suite' ); ?></span></div>
			<div><strong><?php echo esc_html( number_format_i18n( absint( $counts['medium'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'Medium severity', 'noesia-commerce-suite' ); ?></span></div>
		</div>
		<div class="noesia-cs-doctor-list">
			<?php foreach ( $items as $item ) : ?>
				<div class="is-<?php echo esc_attr( $item['severity'] ); ?>">
					<span></span>
					<div>
						<strong><?php echo esc_html( $item['title'] ); ?></strong>
						<small><?php echo esc_html( $item['message'] ); ?></small>
						<?php if ( ! empty( $item['examples'] ) && is_array( $item['examples'] ) ) : ?>
							<ul class="noesia-cs-doctor-examples">
								<?php foreach ( $item['examples'] as $example ) : ?>
									<li>
										<?php if ( ! empty( $example['edit_url'] ) ) : ?>
											<a href="<?php echo esc_url( $example['edit_url'] ); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html( $example['name'] ?? __( 'Product', 'noesia-commerce-suite' ) ); ?></a>
										<?php else : ?>
											<?php echo esc_html( $example['name'] ?? __( 'Product', 'noesia-commerce-suite' ) ); ?>
										<?php endif; ?>
									</li>
								<?php endforeach; ?>
							</ul>
							<?php if ( absint( $item['count'] ?? 0 ) > count( $item['examples'] ) ) : ?>
								<small class="noesia-cs-doctor-examples-note"><?php printf( /* translators: 1: first numeric value; 2: second numeric value. */ esc_html__( 'Showing first %1$d examples from %2$d affected items.', 'noesia-commerce-suite' ), count( $item['examples'] ), absint( $item['count'] ?? 0 ) ); ?></small>
							<?php endif; ?>
						<?php endif; ?>
						<?php if ( ! empty( $item['code'] ) && 'clean' !== $item['code'] && 'scan_error' !== $item['code'] && absint( $item['count'] ?? 0 ) > 0 ) : ?>
							<div class="noesia-cs-doctor-row-actions">
								<a class="noesia-cs-mini-link" href="<?php echo esc_url( add_query_arg( array(
									'page'                    => 'noesia-commerce-suite',
									'tab'                     => 'ecommerce-doctor',
									'noesia_cs_doctor_issue'  => sanitize_key( $item['code'] ),
								), admin_url( 'admin.php' ) ) . '#noesia-cs-doctor-details' ); ?>"><?php esc_html_e( 'View details', 'noesia-commerce-suite' ); ?></a>
								<a class="noesia-cs-mini-link" href="<?php echo esc_url( wp_nonce_url( add_query_arg( array(
									'action'                  => 'noesia_cs_doctor_export_issue',
									'noesia_cs_doctor_issue'  => sanitize_key( $item['code'] ),
								), admin_url( 'admin-post.php' ) ), 'noesia_cs_doctor_export_' . sanitize_key( $item['code'] ) ) ); ?>"><?php esc_html_e( 'Export CSV', 'noesia-commerce-suite' ); ?></a>
							</div>
						<?php endif; ?>
					</div>
					<em><?php echo esc_html( ucfirst( $item['severity'] ) ); ?></em>
				</div>
			<?php endforeach; ?>
			<?php if ( empty( $items ) ) : ?>
				<p><?php esc_html_e( 'Run the first manual scan to see ecommerce health warnings.', 'noesia-commerce-suite' ); ?></p>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $order Order.
	 */
	public function safe_customer_label( $order ) {
		$name = trim( $order->get_billing_first_name() . ' ' . substr( $order->get_billing_last_name(), 0, 1 ) );
		return $name ? $name . '.' : __( 'Customer', 'noesia-commerce-suite' );
	}



	/**
	 * Handles the related plugin operation.
	 */
	public function render_system_status_panel() {
		$status = $this->system_status_service->get_status();
		?>
		<div class="noesia-cs-panel noesia-cs-system-status">
			<div class="noesia-cs-panel__head">
				<h2><?php esc_html_e( 'System Status & Compatibility', 'noesia-commerce-suite' ); ?></h2>
				<span><?php printf( /* translators: %s: dynamic value. */ esc_html__( 'Version %s', 'noesia-commerce-suite' ), esc_html( $status['plugin_version'] ) ); ?></span>
			</div>
			<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Operational checks use real WordPress, WooCommerce and cached store state. They are not demo indicators.', 'noesia-commerce-suite' ); ?></p>
			<div class="noesia-cs-status-grid">
				<?php foreach ( $status['checks'] as $check ) : ?>
					<div class="noesia-cs-status-card is-<?php echo esc_attr( $check['status'] ); ?>">
						<strong><?php echo esc_html( $check['label'] ); ?></strong>
						<span><?php echo esc_html( $check['message'] ); ?></span>
					</div>
				<?php endforeach; ?>
			</div>
			<div class="noesia-cs-endpoint-grid">
				<div><span><?php esc_html_e( 'Care endpoint', 'noesia-commerce-suite' ); ?></span><small><?php esc_html_e( 'Secure public URL pattern for customer Order Care Hub pages.', 'noesia-commerce-suite' ); ?></small><code><?php echo esc_html( $status['care_endpoint'] ); ?></code></div>
				<div><span><?php esc_html_e( 'Opt-out endpoint', 'noesia-commerce-suite' ); ?></span><small><?php esc_html_e( 'Customer unsubscribe URL pattern for reorder reminder emails.', 'noesia-commerce-suite' ); ?></small><code><?php echo esc_html( $status['optout_endpoint'] ); ?></code></div>
				<div><span><?php esc_html_e( 'Care action endpoint', 'noesia-commerce-suite' ); ?></span><small><?php esc_html_e( 'Internal tracked-action URL pattern for review, reorder and support clicks.', 'noesia-commerce-suite' ); ?></small><code><?php echo esc_html( $status['care_action_endpoint'] ); ?></code></div>
				<div><span><?php esc_html_e( 'Impact shortcode', 'noesia-commerce-suite' ); ?></span><small><?php esc_html_e( 'Primary shortcode for the public privacy-safe Impact Map.', 'noesia-commerce-suite' ); ?></small><code><?php echo esc_html( $status['impact_shortcode'] ); ?></code></div>
				<div><span><?php esc_html_e( 'Alias shortcode', 'noesia-commerce-suite' ); ?></span><small><?php esc_html_e( 'Secondary shortcode alias kept for prefix consistency.', 'noesia-commerce-suite' ); ?></small><code><?php echo esc_html( $status['impact_alias'] ); ?></code></div>
			</div>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="noesia-cs-inline-action">
				<?php wp_nonce_field( 'noesia_cs_refresh_rewrites' ); ?>
				<input type="hidden" name="action" value="noesia_cs_refresh_rewrites">
				<button class="noesia-cs-secondary-button" type="submit"><?php esc_html_e( 'Refresh Care Endpoint Rules', 'noesia-commerce-suite' ); ?></button>
				<small><?php esc_html_e( 'Use only if care or opt-out URLs return 404 after moving the plugin or changing permalink settings.', 'noesia-commerce-suite' ); ?></small>
			</form>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 */
	public function render_upgrade_summary() {
		$catalog = $this->feature_service->get_catalog();
		?>
		<div class="noesia-cs-panel noesia-cs-pro-matrix">
			<div class="noesia-cs-panel__head">
				<h2><?php esc_html_e( 'Professional Expansion Areas', 'noesia-commerce-suite' ); ?></h2>
				<span><?php echo esc_html( $this->feature_service->get_plan_label() ); ?></span>
			</div>
			<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'These are separate Pro Edition expansion areas. The Free Core remains usable on its own, and premium code is expected to live outside the WordPress.org free package.', 'noesia-commerce-suite' ); ?></p>
			<div class="noesia-cs-pro-matrix__grid">
				<?php foreach ( $catalog as $key => $feature ) : ?>
					<div class="noesia-cs-pro-matrix__item <?php echo $this->feature_service->can_use( $key ) ? 'is-active' : 'is-explore'; ?>">
						<span><?php echo esc_html( $feature['area'] ); ?></span>
						<strong><?php echo esc_html( $feature['title'] ); ?></strong>
						<small><?php echo esc_html( $feature['description'] ); ?></small>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}


	/**
	 * Handles the related plugin operation.
	 */
	public function render_settings_binding_panel() {
		$report  = $this->settings_binding_service->get_report( $this->settings_sections(), $this->field_labels() );
		$counts  = isset( $report['counts'] ) ? $report['counts'] : array();
		$rows    = isset( $report['rows'] ) && is_array( $report['rows'] ) ? $report['rows'] : array();
		$attention = array_values(
			array_filter(
				$rows,
				function ( $row ) {
					return isset( $row['status'] ) && 'needs-review' === $row['status'];
				}
			)
		);
		?>
		<details class="noesia-cs-panel noesia-cs-settings-binding noesia-cs-developer-diagnostics noesia-cs-settings-connection-check">
			<summary class="noesia-cs-developer-diagnostics__summary">
				<div>
					<h2><?php esc_html_e( 'Settings Connection Check', 'noesia-commerce-suite' ); ?></h2>
					<span><?php esc_html_e( 'Developer / owner diagnostic', 'noesia-commerce-suite' ); ?></span>
				</div>
				<b><?php esc_html_e( 'Open check', 'noesia-commerce-suite' ); ?></b>
			</summary>
			<div class="noesia-cs-developer-diagnostics__body">
				<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Internal check that shows whether saved settings are connected to runtime behavior or documented as policy controls. This is a developer/owner diagnostic, not a customer-facing feature.', 'noesia-commerce-suite' ); ?></p>
			<div class="noesia-cs-binding-metrics">
				<div><strong><?php echo esc_html( number_format_i18n( absint( $counts['total'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'registered settings', 'noesia-commerce-suite' ); ?></span></div>
				<div><strong><?php echo esc_html( number_format_i18n( absint( $counts['in_form'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'shown in Settings', 'noesia-commerce-suite' ); ?></span></div>
				<div><strong><?php echo esc_html( number_format_i18n( absint( $counts['runtime_bound'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'runtime-bound', 'noesia-commerce-suite' ); ?></span></div>
				<div><strong><?php echo esc_html( number_format_i18n( absint( $counts['policy_bound'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'policy-bound', 'noesia-commerce-suite' ); ?></span></div>
				<div><strong><?php echo esc_html( number_format_i18n( absint( $counts['needs_review'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'need review', 'noesia-commerce-suite' ); ?></span></div>
			</div>
			<?php if ( ! empty( $attention ) ) : ?>
				<div class="noesia-cs-binding-list">
					<h3><?php esc_html_e( 'Settings that still need explicit runtime review', 'noesia-commerce-suite' ); ?></h3>
					<?php foreach ( array_slice( $attention, 0, 18 ) as $row ) : ?>
						<div class="noesia-cs-binding-row is-<?php echo esc_attr( $row['status'] ); ?>">
							<div><strong><?php echo esc_html( $row['label'] ); ?></strong><code><?php echo esc_html( $row['key'] ); ?></code></div>
							<span><?php echo esc_html( $row['section'] ); ?></span>
							<small><?php echo esc_html( $row['note'] ); ?></small>
						</div>
					<?php endforeach; ?>
					<?php if ( count( $attention ) > 18 ) : ?>
						<p class="noesia-cs-panel__body-note"><?php printf( /* translators: %d: numeric value. */ esc_html__( '%d more settings need review. Continue the next hardening pass before adding new feature layers.', 'noesia-commerce-suite' ), absint( count( $attention ) - 18 ) ); ?></p>
					<?php endif; ?>
				</div>
			<?php else : ?>
				<p class="noesia-cs-binding-ok"><?php esc_html_e( 'All registered settings are either runtime-bound or documented as policy-bound in this build.', 'noesia-commerce-suite' ); ?></p>
			<?php endif; ?>
			</div>
		</details>
		<?php
	}


	/**
	 * Handles the related plugin operation.
	 */
	public function render_service_boundary_panel() {
		if ( ! $this->service_boundary_service || ! method_exists( $this->service_boundary_service, 'get_report' ) ) {
			return;
		}

		$report    = $this->service_boundary_service->get_report( $this->container, $this->module_registry );
		$totals    = isset( $report['totals'] ) && is_array( $report['totals'] ) ? $report['totals'] : array();
		$services  = isset( $report['services'] ) && is_array( $report['services'] ) ? $report['services'] : array();
		$modules   = isset( $report['modules'] ) && is_array( $report['modules'] ) ? $report['modules'] : array();
		?>
		<details class="noesia-cs-panel noesia-cs-service-boundary noesia-cs-developer-diagnostics">
			<summary class="noesia-cs-developer-diagnostics__summary">
				<div>
					<h2><?php esc_html_e( 'Developer Diagnostics', 'noesia-commerce-suite' ); ?></h2>
					<span><?php esc_html_e( 'System Architecture Status', 'noesia-commerce-suite' ); ?></span>
				</div>
				<b><?php esc_html_e( 'Open diagnostics', 'noesia-commerce-suite' ); ?></b>
			</summary>
			<div class="noesia-cs-developer-diagnostics__body">
				<p class="noesia-cs-panel__body-note"><?php esc_html_e( 'Internal diagnostic check for developers and site owners. It verifies whether the module registry, views, services and repositories are loaded correctly. This is not a customer-facing commerce feature.', 'noesia-commerce-suite' ); ?></p>
				<div class="noesia-cs-binding-metrics noesia-cs-boundary-metrics">
					<div><strong><?php echo esc_html( number_format_i18n( absint( $totals['services_ok'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'services OK', 'noesia-commerce-suite' ); ?></span></div>
					<div><strong><?php echo esc_html( number_format_i18n( absint( $totals['services_warning'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'service warnings', 'noesia-commerce-suite' ); ?></span></div>
					<div><strong><?php echo esc_html( number_format_i18n( absint( $totals['modules_ok'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'modules OK', 'noesia-commerce-suite' ); ?></span></div>
					<div><strong><?php echo esc_html( number_format_i18n( absint( $totals['modules_warning'] ?? 0 ) ) ); ?></strong><span><?php esc_html_e( 'module warnings', 'noesia-commerce-suite' ); ?></span></div>
				</div>
				<div class="noesia-cs-boundary-columns">
					<div>
						<h3><?php esc_html_e( 'Service / Repository Boundaries', 'noesia-commerce-suite' ); ?></h3>
						<div class="noesia-cs-boundary-list">
							<?php foreach ( $services as $service ) : ?>
								<div class="noesia-cs-boundary-row is-<?php echo esc_attr( $service['status'] ); ?>">
									<div>
										<strong><?php echo esc_html( $service['label'] ); ?></strong>
										<code><?php echo esc_html( $service['key'] ); ?></code>
									</div>
									<span><?php echo esc_html( $service['role'] ); ?></span>
									<small><?php echo esc_html( $service['message'] ); ?></small>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
					<div>
						<h3><?php esc_html_e( 'Admin Module Boundaries', 'noesia-commerce-suite' ); ?></h3>
						<div class="noesia-cs-boundary-list">
							<?php foreach ( $modules as $module ) : ?>
								<div class="noesia-cs-boundary-row is-<?php echo esc_attr( $module['status'] ); ?>">
									<div>
										<strong><?php echo esc_html( $module['label'] ); ?></strong>
										<code><?php echo esc_html( $module['key'] ); ?></code>
									</div>
									<span><?php echo esc_html( $module['view'] ); ?></span>
									<small><?php echo esc_html( $module['message'] ); ?></small>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
				</div>
			</div>
		</details>
		<?php
	}


	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $forecast Forecast.
	 */
	public function render_weather_forecast( $forecast ) {
		$forecast = is_array( $forecast ) ? $forecast : array();
		if ( empty( $forecast['enabled'] ) && 'disabled' === ( $forecast['status'] ?? 'disabled' ) ) {
			return;
		}
		$status  = sanitize_key( $forecast['status'] ?? 'disabled' );
		$days    = isset( $forecast['days'] ) && is_array( $forecast['days'] ) ? array_slice( $forecast['days'], 0, 7 ) : array();
		?>
		<section class="noesia-cs-weather-panel noesia-cs-weather-panel--<?php echo esc_attr( $status ); ?>">
			<div class="noesia-cs-weather-panel__sky"></div>
			<div class="noesia-cs-weather-panel__head">
				<div>
					<a class="noesia-cs-weather-settings-link" href="<?php echo esc_url( $this->settings_section_url( 'dashboard-weather-settings' ) ); ?>"><?php esc_html_e( 'Change town', 'noesia-commerce-suite' ); ?></a>
					<h2><?php esc_html_e( '7-Day Weather Forecast', 'noesia-commerce-suite' ); ?></h2>
					<p><?php esc_html_e( 'A beautiful weekly outlook for store operations, deliveries and planning.', 'noesia-commerce-suite' ); ?></p>
				</div>
				<?php if ( ! empty( $forecast['location'] ) ) : ?>

					<strong><?php echo esc_html( $forecast['location'] ); ?></strong>

				<?php endif; ?>
			</div>
			<?php if ( 'ok' !== $status || empty( $days ) ) : ?>
				<div class="noesia-cs-weather-empty">
					<strong><?php esc_html_e( 'Weather forecast is not active yet.', 'noesia-commerce-suite' ); ?></strong>
					<p><?php echo esc_html( $forecast['message'] ?? __( 'Enable dashboard weather and add a city/country or coordinates in Settings.', 'noesia-commerce-suite' ) ); ?></p>
				</div>
			<?php else : ?>
				<div class="noesia-cs-weather-days">
					<?php foreach ( $days as $day ) : ?>
						<article class="noesia-cs-weather-card <?php echo ! empty( $day['is_today'] ) ? 'is-today' : ''; ?>">
							<h3><?php echo esc_html( $day['label'] ?? '' ); ?></h3>
							<div class="noesia-cs-weather-icon"><?php echo esc_html( $day['icon'] ?? '•' ); ?></div>
							<strong><?php echo esc_html( $day['condition'] ?? __( 'Forecast', 'noesia-commerce-suite' ) ); ?></strong>
							<div class="noesia-cs-weather-temps">
								<span><?php esc_html_e( 'Max', 'noesia-commerce-suite' ); ?> <b><?php echo is_null( $day['max'] ) ? '—' : esc_html( $day['max'] . '°C' ); ?></b></span>
								<span><?php esc_html_e( 'Min', 'noesia-commerce-suite' ); ?> <b><?php echo is_null( $day['min'] ) ? '—' : esc_html( $day['min'] . '°C' ); ?></b></span>
							</div>
							<div class="noesia-cs-weather-rain"><span>◆</span><?php esc_html_e( 'Rain', 'noesia-commerce-suite' ); ?> <b><?php echo is_null( $day['rain'] ) ? '—' : esc_html( $day['rain'] . '%' ); ?></b></div>
						</article>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>
		</section>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $context Context.
	 */
	public function settings_sections( $context = 'all' ) {
		$sections = array(
			'general'          => array( 'title' => __( 'General / Branding', 'noesia-commerce-suite' ), 'fields' => array( 'company_name', 'company_logo', 'primary_color', 'accent_color', 'button_style', 'contact_text', 'support_email', 'phone_contact_text', 'show_woo_care_button' ) ),
			'order_care_hub'   => array(
							'title'           => __( 'Order Care Hub Settings', 'noesia-commerce-suite' ),
							'fields'          => array(
								'enable_care_page',
								'enable_review_block',
								'review_button_label',
								'review_intro_text',
								'google_review_url',
								'trustpilot_url',
								'store_review_url',
								'show_reorder_button',
								'reorder_button_behavior',
								'enable_support_block',
								'support_button_label',
								'support_intro_text',
								'support_action_type',
								'support_email',
								'support_url',
								'care_action_tracking_enabled',
								'order_care_warranty_enabled',
								'order_care_warranty_title',
								'order_care_warranty_text',
								'order_care_warranty_button_label',
								'order_care_warranty_url',
								'order_care_documents_enabled',
								'order_care_documents_title',
								'order_care_documents_text',
								'order_care_documents_button_label',
								'order_care_documents_url',
								'order_care_video_enabled',
								'order_care_video_title',
								'order_care_video_text',
								'order_care_video_button_label',
								'order_care_video_url',
								'order_care_promo_enabled',
								'order_care_promo_title',
								'order_care_promo_text',
								'order_care_promo_code',
								'order_care_promo_button_label',
								'order_care_promo_url',
								'enable_product_passport_qr',
								'thankyou_integration',
								'show_qr_thankyou',
								'email_integration',
								'show_qr_emails',
								'my_account_integration',
								'show_qr_my_account',
								'order_admin_metabox',
								'show_qr_order_admin',
								'show_woo_care_button',
								'allow_printable_qr',
								'qr_size',
								'qr_foreground_color',
								'qr_background_color',
								'qr_label_text',
								'order_care_public_style',
								'order_care_button_style',
								'order_care_content_width',
								'button_style',
								'qr_card_layout_style',
								'order_care_access_card_title',
								'order_care_access_card_text',
								'order_care_access_button_label',
								'company_logo',
								'primary_color',
								'accent_color',
								'show_product_name',
								'show_order_number',
								'show_purchase_date',
								'show_verified_badge',
								'care_page_title_text',
								'care_page_intro_text',
								'privacy_noindex',
								'require_login_care_page',
			'privacy_hide_full_name',
								'privacy_hide_address',
								'privacy_hide_email',
								'privacy_hide_phone',
								'secure_token_behavior',
							),
						),
			'reorder'     => array(
							'title'        => __( 'Reorder Settings', 'noesia-commerce-suite' ),
							'description'  => __( 'Controls optional replacement reminder processing and the public Order Again behavior. Keep reminders disabled unless the store wants scheduled reorder emails.', 'noesia-commerce-suite' ),
							'fields'       => array( 'reorder_reminders_enabled', 'reorder_email_enabled', 'reorder_opt_out_enabled', 'reorder_default_days', 'reorder_batch_size', 'reorder_button_behavior', 'reorder_checkout_request_enabled', 'reorder_checkout_badge_label', 'reorder_checkout_label', 'reorder_checkout_info_text', 'reorder_checkout_date_label' ),
						),
			'analytics'      => array( 'title' => __( 'Intelligence / Analytics Settings', 'noesia-commerce-suite' ), 'fields' => array( 'analytics_default_range', 'show_analytics_revenue', 'show_analytics_top_customers', 'show_analytics_top_cities', 'show_analytics_products', 'show_analytics_categories', 'analytics_cache_minutes' ) ),
			'weather'        => array( 'title' => __( 'Dashboard Weather Settings', 'noesia-commerce-suite' ), 'fields' => array( 'dashboard_weather_enabled', 'dashboard_weather_location_label', 'dashboard_weather_location_search', 'dashboard_weather_latitude', 'dashboard_weather_longitude', 'dashboard_weather_cache_minutes' ) ),
			'impact'         => array( 'title' => __( 'Impact Map Settings', 'noesia-commerce-suite' ), 'fields' => array( 'enable_impact_map_shortcode', 'impact_map_cache_enabled', 'impact_map_style', 'impact_map_background_size', 'impact_map_max_visible_areas', 'impact_map_public_eyebrow', 'impact_map_public_title', 'impact_map_public_subtitle', 'impact_map_threshold', 'impact_snapshot_order_limit', 'impact_map_group_by', 'impact_map_show_orders', 'impact_map_show_products', 'impact_map_show_top_categories', 'impact_map_show_top_products', 'impact_map_show_revenue' ) ),
			'doctor'         => array( 'title' => __( 'Ecommerce Doctor Settings', 'noesia-commerce-suite' ), 'fields' => array( 'enable_doctor_scan', 'doctor_scan_without_image', 'doctor_scan_without_price', 'doctor_scan_without_sku', 'doctor_scan_without_category', 'doctor_scan_short_description', 'doctor_scan_large_images', 'doctor_scan_missing_alt', 'doctor_scan_missing_shipping_data', 'doctor_scan_missing_related_products', 'doctor_scan_hidden_in_stock', 'doctor_scan_visible_out_of_stock', 'doctor_scan_suspicious_order_signals', 'doctor_scan_data_retention_review', 'doctor_data_retention_months', 'doctor_scan_temporary_data', 'doctor_scan_autoloaded_options', 'doctor_scan_action_scheduler_queue', 'doctor_scan_broken_links', 'doctor_broken_link_limit', 'doctor_check_wc_pages', 'doctor_product_scan_limit', 'doctor_large_image_kb', 'doctor_result_retention_days', 'doctor_severity_threshold' ) ),
			'emails'         => array( 'title' => __( 'Email Settings', 'noesia-commerce-suite' ), 'fields' => array( 'passport_email_enabled', 'email_logo', 'email_button_color', 'email_sender_name', 'test_email_recipient', 'passport_email_subject', 'passport_email_body', 'passport_email_button_label', 'email_footer_text' ) ),
			'privacy'        => array(
							'title'        => __( 'Privacy Settings', 'noesia-commerce-suite' ),
							'description'  => __( 'Controls public privacy defaults, log retention and the optional uninstall cleanup. Public Order Care Hub identity/privacy controls live under Order Care Hub > Security & Visibility.', 'noesia-commerce-suite' ),
							'fields'       => array( 'privacy_hide_full_name', 'privacy_hide_address', 'privacy_hide_email', 'privacy_hide_phone', 'privacy_hide_revenue_public', 'secure_token_behavior', 'logs_retention_days', 'delete_data_on_uninstall' ),
						),
			'compatibility' => array( 'title' => __( 'Compatibility Settings', 'noesia-commerce-suite' ), 'fields' => array( 'wc_status_check', 'hpos_status_check' ) ),
		);

		if ( 'settings' === $context ) {
			unset( $sections['order_care_hub'], $sections['reorder'] );

			if ( isset( $sections['general']['fields'] ) ) {
				$sections['general']['fields'] = array_values( array_diff( $sections['general']['fields'], array( 'support_email', 'show_woo_care_button' ) ) );
			}

			unset( $sections['emails'] );

			if ( isset( $sections['privacy']['fields'] ) ) {
				$sections['privacy']['fields'] = array_values( array_diff( $sections['privacy']['fields'], array( 'privacy_hide_full_name', 'privacy_hide_address', 'privacy_hide_email', 'privacy_hide_phone', 'secure_token_behavior' ) ) );
			}

			if ( isset( $sections['compatibility']['fields'] ) ) {
				$sections['compatibility']['fields'] = array_values( array_diff( $sections['compatibility']['fields'], array( 'my_account_integration', 'thankyou_integration', 'email_integration', 'order_admin_metabox' ) ) );
			}
		}

		return $sections;
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $skin Skin.
	 * @param mixed $title Title.
	 * @param mixed $description Description.
	 * @param mixed $fields Fields.
	 * @param mixed $settings Settings.
	 * @param mixed $tab Tab.
	 */
	public function render_settings_group( $skin, $title, $description, $fields, $settings, $tab = '' ) {
		?>
		<section class="noesia-cs-feature-hero noesia-cs-feature-hero--<?php echo esc_attr( $skin ); ?>"><div><span><?php esc_html_e( 'Configuration', 'noesia-commerce-suite' ); ?></span><h2><?php echo esc_html( $title ); ?></h2><p><?php echo esc_html( $description ); ?></p></div></section>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="noesia-cs-settings-form">
			<?php wp_nonce_field( 'noesia_cs_save_settings' ); ?>
			<input type="hidden" name="action" value="noesia_cs_save_settings">
			<input type="hidden" name="noesia_cs_tab" value="<?php echo esc_attr( $tab ? $tab : $skin ); ?>">
			<?php $this->settings_card( $title, $fields, $settings ); ?>
			<div class="noesia-cs-sticky-save"><button class="noesia-cs-primary-button" type="submit"><?php esc_html_e( 'Save Settings', 'noesia-commerce-suite' ); ?></button></div>
		</form>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $title Title.
	 * @param mixed $fields Fields.
	 * @param mixed $settings Settings.
	 * @param mixed $description Description.
	 * @param mixed $section_id Section id.
	 */
	public function settings_card( $title, $fields, $settings, $description = '', $section_id = '' ) {
		?>
		<?php $section_id = $section_id ? sanitize_key( $section_id ) : sanitize_title( $title ); ?>
		<div class="noesia-cs-panel noesia-cs-settings-card noesia-cs-settings-card--<?php echo esc_attr( sanitize_html_class( $section_id ) ); ?>" id="noesia-cs-settings-<?php echo esc_attr( sanitize_key( $section_id ) ); ?>"><div class="noesia-cs-panel__head"><h2><?php echo esc_html( $title ); ?></h2></div><?php if ( $description ) : ?><p class="noesia-cs-settings-card__desc"><?php echo esc_html( $description ); ?></p><?php endif; ?>
			<div class="noesia-cs-fields">
				<?php foreach ( $fields as $field ) : $this->render_field( $field, $settings[ $field ] ?? '' ); endforeach; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $key Key.
	 * @param mixed $value Value.
	 */
	public function render_field( $key, $value ) {
		$labels     = $this->field_labels();
		$label      = $labels[ $key ] ?? ucwords( str_replace( '_', ' ', $key ) );
		$name       = 'noesia_cs_settings[' . esc_attr( $key ) . ']';
		$is_yes_no  = in_array( $value, array( 'yes', 'no' ), true );
		$help       = $this->field_help( $key );
		?>
		<?php $is_locked_privacy = in_array( $key, array( 'privacy_hide_full_name', 'privacy_hide_address', 'privacy_hide_email', 'privacy_hide_phone' ), true ); ?>
		<label class="noesia-cs-field noesia-cs-field--<?php echo esc_attr( sanitize_html_class( $key ) ); ?><?php echo $is_locked_privacy ? ' noesia-cs-field--locked-privacy' : ''; ?>"><span><?php echo esc_html( $label ); ?></span>
		<?php if ( $is_locked_privacy ) : ?>
			<input type="hidden" name="<?php echo esc_attr( $name ); ?>" value="yes">
			<select disabled aria-disabled="true"><option value="yes" selected><?php esc_html_e( 'Enabled', 'noesia-commerce-suite' ); ?></option></select>
		<?php elseif ( $is_yes_no ) : ?>
			<select name="<?php echo esc_attr( $name ); ?>"><option value="yes" <?php selected( $value, 'yes' ); ?>><?php esc_html_e( 'Enabled', 'noesia-commerce-suite' ); ?></option><option value="no" <?php selected( $value, 'no' ); ?>><?php esc_html_e( 'Disabled', 'noesia-commerce-suite' ); ?></option></select>
		<?php elseif ( in_array( $key, array( 'primary_color', 'accent_color', 'email_button_color', 'qr_foreground_color', 'qr_background_color' ), true ) ) : ?>
			<input type="color" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $value ); ?>">
		<?php elseif ( in_array( $key, array( 'button_style', 'support_action_type', 'order_care_public_style', 'order_care_button_style', 'order_care_content_width', 'reorder_button_behavior', 'warranty_calculation_mode', 'analytics_default_range', 'impact_map_group_by', 'impact_map_style', 'impact_map_background_size', 'doctor_severity_threshold', 'qr_card_layout_style', 'secure_token_behavior', 'reorder_checkout_style', 'email_log_retention_days' ), true ) ) : ?>
			<?php $this->render_select_field( $key, $name, $value ); ?>
		<?php elseif ( in_array( $key, array( 'company_logo', 'email_logo' ), true ) ) : ?>
			<div class="noesia-cs-media-url-field">
				<input type="url" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_url( $value ); ?>" data-noesia-cs-media-url>
				<button type="button" class="noesia-cs-secondary-button noesia-cs-media-upload-button" data-noesia-cs-media-upload><?php esc_html_e( 'Choose / Upload', 'noesia-commerce-suite' ); ?></button>
			</div>
		<?php elseif ( false !== strpos( $key, 'url' ) || false !== strpos( $key, 'logo' ) ) : ?>
			<input type="url" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_url( $value ); ?>">
		<?php elseif ( in_array( $key, array( 'support_email', 'test_email_recipient' ), true ) ) : ?>
			<input type="email" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $value ); ?>">
		<?php elseif ( false !== strpos( $key, 'body' ) || false !== strpos( $key, 'text' ) || false !== strpos( $key, 'instructions' ) ) : ?>
			<textarea name="<?php echo esc_attr( $name ); ?>" rows="3"><?php echo esc_textarea( $value ); ?></textarea>
		<?php elseif ( in_array( $key, array( 'dashboard_weather_latitude', 'dashboard_weather_longitude' ), true ) ) : ?>
			<input type="number" step="0.000001" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $value ); ?>">
		<?php elseif ( is_numeric( $value ) ) : ?>
			<input type="number" min="0" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $value ); ?>" <?php echo 'dashboard_weather_cache_minutes' === $key ? 'step="30"' : ''; ?>>
		<?php else : ?>
			<input type="text" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $value ); ?>" <?php echo 'dashboard_weather_location_search' === $key ? 'placeholder="Athens, Greece"' : ''; ?>>
		<?php endif; ?>
		<?php if ( $help ) : ?>
			<small class="noesia-cs-field__help"><?php echo wp_kses_post( $help ); ?></small>
		<?php endif; ?>
		</label>
		<?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $key Key.
	 * @param mixed $name Name.
	 * @param mixed $value Value.
	 */
	private function render_select_field( $key, $name, $value ) {
		if ( 'impact_map_style' === $key && 'map' === $value ) {
			$value = 'noesia_glass';
		}
		$options = array(
			'button_style'                 => array( 'rounded' => __( 'Rounded', 'noesia-commerce-suite' ), 'pill' => __( 'Pill', 'noesia-commerce-suite' ), 'minimal' => __( 'Minimal', 'noesia-commerce-suite' ) ),
			'support_action_type'          => array( 'email' => __( 'Send email', 'noesia-commerce-suite' ), 'url' => __( 'Open custom support URL', 'noesia-commerce-suite' ) ),
			'order_care_public_style'      => array( 'clean' => __( 'Clean', 'noesia-commerce-suite' ), 'compact' => __( 'Compact', 'noesia-commerce-suite' ), 'premium' => __( 'Premium', 'noesia-commerce-suite' ), 'enterprise' => __( 'Enterprise', 'noesia-commerce-suite' ) ),
			'order_care_button_style'      => array( 'solid' => __( 'Solid', 'noesia-commerce-suite' ), 'soft' => __( 'Soft', 'noesia-commerce-suite' ), 'outline' => __( 'Outline', 'noesia-commerce-suite' ) ),
			'order_care_content_width'     => array( 'small' => __( 'Small / Focused', 'noesia-commerce-suite' ), 'medium' => __( 'Medium / Balanced', 'noesia-commerce-suite' ), 'full' => __( 'Full width', 'noesia-commerce-suite' ) ),
			'reorder_button_behavior'      => array( 'product' => __( 'Product page', 'noesia-commerce-suite' ), 'cart' => __( 'Add to cart', 'noesia-commerce-suite' ) ),
			'reorder_checkout_style'        => array( 'clean' => __( 'Clean', 'noesia-commerce-suite' ), 'dark' => __( 'Dark', 'noesia-commerce-suite' ), 'glamour' => __( 'Noesia Glamour', 'noesia-commerce-suite' ) ),
			'warranty_calculation_mode'    => array( 'order_date' => __( 'Order date', 'noesia-commerce-suite' ), 'completed_date' => __( 'Completed date', 'noesia-commerce-suite' ) ),
			'analytics_default_range'      => array( '7' => __( '7 days', 'noesia-commerce-suite' ), '30' => __( '30 days', 'noesia-commerce-suite' ), '90' => __( '90 days', 'noesia-commerce-suite' ), '365' => __( '365 days', 'noesia-commerce-suite' ) ),
			'impact_map_group_by'          => array( 'city' => __( 'City', 'noesia-commerce-suite' ), 'region' => __( 'Region', 'noesia-commerce-suite' ), 'country' => __( 'Country', 'noesia-commerce-suite' ) ),
			'impact_map_style'             => array( 'noesia_glass' => __( 'Noesia Glass', 'noesia-commerce-suite' ), 'dark_map' => __( 'Dark World Map', 'noesia-commerce-suite' ), 'glass' => __( 'Glamour Glass', 'noesia-commerce-suite' ), 'compact' => __( 'Compact Cards', 'noesia-commerce-suite' ) ),
			'impact_map_background_size'   => array( 'small' => __( 'Small', 'noesia-commerce-suite' ), 'medium' => __( 'Medium', 'noesia-commerce-suite' ), 'large' => __( 'Large', 'noesia-commerce-suite' ) ),
			'doctor_severity_threshold'    => array( 'low' => __( 'Low and above', 'noesia-commerce-suite' ), 'medium' => __( 'Medium and above', 'noesia-commerce-suite' ), 'high' => __( 'High only', 'noesia-commerce-suite' ) ),
			'qr_card_layout_style'         => array( 'clean' => __( 'Clean', 'noesia-commerce-suite' ), 'compact' => __( 'Compact', 'noesia-commerce-suite' ) ),
			'secure_token_behavior'        => array( 'active' => __( 'Active secure token links', 'noesia-commerce-suite' ) ),
			'email_log_retention_days'  => array( '7' => __( '7 days', 'noesia-commerce-suite' ), '15' => __( '15 days', 'noesia-commerce-suite' ), '30' => __( '30 days', 'noesia-commerce-suite' ), '60' => __( '60 days', 'noesia-commerce-suite' ), '90' => __( '90 days', 'noesia-commerce-suite' ) ),
		);
		?><select name="<?php echo esc_attr( $name ); ?>"><?php foreach ( $options[ $key ] as $option_value => $option_label ) : ?><option value="<?php echo esc_attr( $option_value ); ?>" <?php selected( $value, $option_value ); ?>><?php echo esc_html( $option_label ); ?></option><?php endforeach; ?></select><?php
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $key Key.
	 */
	private function field_help( $key ) {
		$google_maps_coordinates_url = 'https://support.google.com/maps/answer/18539?hl=en';
		$help = array(
			'dashboard_weather_location_search'  => __( 'Use a clear city and country in English. Recommended examples: Athens, Greece · Rome, Italy · Paris, France. Two-letter country codes such as IT or FR can also work, but full country names are safer.', 'noesia-commerce-suite' ),
			'dashboard_weather_location_label'   => __( 'Optional display label shown on the weather panel. Leave the location search field responsible for finding the forecast.', 'noesia-commerce-suite' ),
			'dashboard_weather_latitude'         => sprintf(
							/* translators: %s: Google Maps support link. */
							__( 'Optional manual override. Use decimal degrees, latitude first. <a href="%s" target="_blank" rel="noopener noreferrer">Find coordinates with the official Google Maps guide</a>.', 'noesia-commerce-suite' ),
							esc_url( $google_maps_coordinates_url )
						),
			'dashboard_weather_longitude'       => sprintf(
							/* translators: %s: Google Maps support link. */
							__( 'Optional manual override. Use decimal degrees, longitude second. <a href="%s" target="_blank" rel="noopener noreferrer">Find coordinates with the official Google Maps guide</a>.', 'noesia-commerce-suite' ),
							esc_url( $google_maps_coordinates_url )
						),
			'dashboard_weather_cache_minutes'       => __( 'Cache duration in minutes. Recommended: 180 to 720. Two days is 2880 minutes and works, but the forecast will stay less fresh until the cache expires.', 'noesia-commerce-suite' ),
			'test_email_recipient'                  => __( 'Enter the store owner or admin inbox that should receive one verification email. This only chooses the test recipient; it does not improve spam placement. For deliverability, configure authenticated SMTP and SPF, DKIM and DMARC for the sender domain.', 'noesia-commerce-suite' ),
			'show_woo_care_button'                  => __( 'Shows a prominent Open Noesia Care Hub button inside WooCommerce order screens and customer user profiles. The button uses a privileged nonce-protected admin action and creates a secure care token only when needed.', 'noesia-commerce-suite' ),
			'company_logo'                          => __( 'Upload from the WordPress Media Library or paste a logo URL. Recommended: transparent PNG/SVG, square 512×512 for icon logos or up to 900×300 for wide logos.', 'noesia-commerce-suite' ),
			'enable_review_block'                   => __( 'Controls the Leave a Review box in the public Order Care Hub. The box is hidden only for cancelled, refunded or failed orders.', 'noesia-commerce-suite' ),
			'show_reorder_button'                   => __( 'Controls the Order Again box in the public Order Care Hub. Single-product orders show one action; multi-product orders show a small list with one Reorder action per item.', 'noesia-commerce-suite' ),
			'enable_support_block'                  => __( 'Controls the Need Help box in the public Order Care Hub.', 'noesia-commerce-suite' ),
			'care_action_tracking_enabled'          => __( 'When enabled, Review, Reorder and Need Help clicks are logged for private admin activity insights. It does not expose customer details publicly.', 'noesia-commerce-suite' ),
			'support_action_type'                   => __( 'Choose whether the Need Help box opens a prefilled support email or a custom support form URL. The public mailto flow includes the order number in the email subject so the store can identify the request immediately.', 'noesia-commerce-suite' ),
			'reorder_reminders_enabled'             => __( 'Enables customer reorder reminders. It does not send emails unless reminder email is also enabled and a customer reminder is ready.', 'noesia-commerce-suite' ),
			'reorder_email_enabled'                 => __( 'Allows reminder emails to be sent only when a customer has asked for a future reorder reminder. It does not email every customer automatically.', 'noesia-commerce-suite' ),
			'reorder_checkout_request_enabled'      => __( 'Shows an optional checkbox in classic WooCommerce checkout. If the customer opts in and selects a future date, Noesia saves one reminder for that order.', 'noesia-commerce-suite' ),
			'reorder_checkout_badge_label'          => __( 'Small badge shown above the checkout reminder box in the Glamour style. Use your own store words, for example Smart Reminder, Refill Reminder or Beauty Reminder.', 'noesia-commerce-suite' ),
			'reorder_checkout_label'                => __( 'Customer-facing checkbox label shown in checkout.', 'noesia-commerce-suite' ),
			'reorder_checkout_info_text'            => __( 'Short explanation below the checkout checkbox. Tell customers they will receive the reminder email on the selected date.', 'noesia-commerce-suite' ),
			'reorder_checkout_date_label'           => __( 'Label for the date picker shown after the customer ticks the reminder checkbox.', 'noesia-commerce-suite' ),
			'reorder_checkout_style'                => __( 'Choose how the reminder box looks in checkout. Clean is simple, Dark is premium, and Noesia Glamour gives a stronger colorful visual style.', 'noesia-commerce-suite' ),
			'reorder_opt_out_enabled'               => __( 'Adds an opt-out link inside reorder reminder emails only. It does not affect the normal Order Again button in the public Order Care Hub.', 'noesia-commerce-suite' ),
			'reorder_default_days'                  => __( 'Legacy fallback delay. Customer-requested checkout reminders use the date selected by the customer.', 'noesia-commerce-suite' ),
			'reorder_batch_size'                    => __( 'Maximum reminder emails handled during one automatic check. Keep this moderate for shared hosting and large stores.', 'noesia-commerce-suite' ),
			'reorder_button_behavior'               => __( 'Controls where reorder links send customers: the product page or an add-to-cart link. Used by the public hub and reorder reminder emails.', 'noesia-commerce-suite' ),
			'order_care_warranty_url'               => __( 'Link to one clear warranty, returns or guarantee policy page on your store website. Customers open that page from the Order Care Hub.', 'noesia-commerce-suite' ),
			'order_care_documents_url'              => __( 'Link to one categorized manuals/documents page on your store website. Keep product-specific organization on that page, not inside the plugin.', 'noesia-commerce-suite' ),
			'order_care_video_url'                  => __( 'Link to one video guide page, playlist or tutorial page. If empty or disabled, the block is hidden.', 'noesia-commerce-suite' ),
			'order_care_promo_url'                  => __( 'Optional destination for the promo block. If the promo is disabled or has no content, it will be hidden.', 'noesia-commerce-suite' ),
			'order_care_public_style'               => __( 'Scope: public Order Care Hub page only. Clean keeps the current layout, Compact makes it tighter, Premium adds a dark/glass style, and Enterprise uses a black executive look.', 'noesia-commerce-suite' ),
			'order_care_button_style'               => __( 'Scope: public Order Care Hub page only. Changes the visual treatment of the hub action cards and public hub links.', 'noesia-commerce-suite' ),
			'order_care_content_width'              => __( 'Scope: public Order Care Hub page only. Applies to Clean, Compact, Premium and Enterprise layouts.', 'noesia-commerce-suite' ),
			'allow_printable_qr'                    => __( 'Enables printable package QR actions in admin rows. The QR points to the secure Order Care Hub link for an order.', 'noesia-commerce-suite' ),
			'qr_size'                               => __( 'Pixel size used for generated QR blocks and printable QR output.', 'noesia-commerce-suite' ),
			'qr_foreground_color'                   => __( 'Foreground color used by the local QR renderer.', 'noesia-commerce-suite' ),
			'qr_background_color'                   => __( 'Background color used by the local QR renderer. Keep strong contrast for scanning reliability.', 'noesia-commerce-suite' ),
			'qr_label_text'                         => __( 'Fallback QR label used by printable/package QR output. The Thank You/My Account access card uses the customer access text fields below.', 'noesia-commerce-suite' ),
			'button_style'                          => __( 'Scope: both the public Order Care Hub and the Thank You/My Account access card. Customer emails use the separate Email Button Color setting for safe email-client rendering.', 'noesia-commerce-suite' ),
			'qr_card_layout_style'                  => __( 'Scope: WooCommerce Thank You Page and My Account access card only. Customer emails keep a safe fixed email layout.', 'noesia-commerce-suite' ),
			'order_care_access_card_title'          => __( 'Scope: WooCommerce Thank You Page and My Account access card. Customer emails use the email subject/body fields instead.', 'noesia-commerce-suite' ),
			'order_care_access_card_text'           => __( 'Scope: WooCommerce Thank You Page and My Account access card. It does not change the public hub page body or the email body.', 'noesia-commerce-suite' ),
			'order_care_access_button_label'        => __( 'Scope: WooCommerce Thank You Page and My Account access card only.', 'noesia-commerce-suite' ),
			'require_login_care_page'               => __( 'If enabled, token links require a logged-in customer account that owns the order, or an authorized admin. For printed package QR, keep this disabled unless your store requires login-only access.', 'noesia-commerce-suite' ),
			'email_log_retention_days'              => __( 'Choose how many days Noesia keeps recent sent/failed email results. This is only history for the store owner; it does not stop emails, delete orders, or change customer reminders.', 'noesia-commerce-suite' ),
			'privacy_hide_full_name'                => __( 'Keep enabled. The public hub should not display the customer’s full name.', 'noesia-commerce-suite' ),
			'privacy_hide_address'                  => __( 'Keep enabled. The public hub should not display billing or shipping addresses.', 'noesia-commerce-suite' ),
			'privacy_hide_email'                    => __( 'Keep enabled. The public hub should not display customer email addresses.', 'noesia-commerce-suite' ),
			'privacy_hide_phone'                    => __( 'Keep enabled. The public hub should not display customer phone numbers.', 'noesia-commerce-suite' ),
			'delete_data_on_uninstall'                => __( 'Default is Disabled. If enabled, uninstall removes Noesia Commerce Suite settings, reminder history, plugin reports, cache and plugin transients only. It never deletes WooCommerce orders, products, customers, coupons, payments or active WordPress users.', 'noesia-commerce-suite' ),
			'wc_status_check'                       => __( 'Recommended: Enabled. Shows safe admin warnings when WooCommerce is missing or not ready, instead of failing silently.', 'noesia-commerce-suite' ),
			'doctor_scan_missing_shipping_data'     => __( 'Checks shippable products without weight or dimensions. This is important for stores that rely on carrier or weight-based shipping calculations.', 'noesia-commerce-suite' ),
			'doctor_scan_missing_related_products'  => __( 'Checks products without cross-sells or upsells. This is an opportunity signal for average order value, not a technical error.', 'noesia-commerce-suite' ),
			'doctor_scan_hidden_in_stock'           => __( 'Checks products that are in stock but hidden from the catalog. These may be forgotten sellable products.', 'noesia-commerce-suite' ),
			'doctor_scan_visible_out_of_stock'      => __( 'Checks out-of-stock products that are still visible in the catalog. This does not claim they have been out of stock for months; it only reports their current visible state.', 'noesia-commerce-suite' ),
			'doctor_scan_suspicious_order_signals'  => __( 'Read-only recent order review. Flags risk signals such as disposable email domains or generic-looking names. These are signals only, not proof of fraud.', 'noesia-commerce-suite' ),
			'doctor_scan_data_retention_review'     => __( 'Read-only reminder to review old failed, cancelled or refunded orders according to your store data retention policy. Do not delete records required for accounting, tax, warranty or legal obligations.', 'noesia-commerce-suite' ),
			'doctor_data_retention_months'          => __( 'Age threshold for the data retention review. Example: 24 means cancelled, failed or refunded orders older than 24 months are reported for review.', 'noesia-commerce-suite' ),
			'doctor_scan_temporary_data'            => __( 'Read-only count of expired WordPress transients and WooCommerce session records. Helps review temporary data that can accumulate over time; the plugin reports it but does not delete anything.', 'noesia-commerce-suite' ),
			'doctor_scan_autoloaded_options'        => __( 'Read-only WordPress performance check. Autoloaded options are loaded on every request; very large totals can increase memory usage and slow admin or storefront pages.', 'noesia-commerce-suite' ),
			'doctor_scan_action_scheduler_queue'    => __( 'Read-only WooCommerce background-task health check. Many failed or pending background tasks can indicate broken integrations, delayed automation, webhooks or email jobs.', 'noesia-commerce-suite' ),
			'doctor_scan_broken_links'              => __( 'Performs real HTTP checks against product URLs. Broken product pages can hurt trust and block sales paths. Keep disabled for very fast scans, or enable with a safe Quick Scan URL scope for manual audits.', 'noesia-commerce-suite' ),
			'doctor_broken_link_limit'              => __( 'Number of product URLs checked with real HTTP requests during one manual scan. Manual scans use a 15-URL Quick Scan scope to avoid timeouts.', 'noesia-commerce-suite' ),
			'doctor_product_scan_limit'             => __( 'Number of published products loaded for normal product-data checks. Manual scans use a 300-product Quick Scan scope for memory safety. This is separate from the Broken Link URL Scope, because link checks perform real HTTP requests.', 'noesia-commerce-suite' ),
			'impact_map_style'                      => __( 'Choose the public visual style for the Impact Map. Dark World Map uses local plugin assets only; no external map APIs, tiles or CDNs are loaded.', 'noesia-commerce-suite' ),
			'hpos_status_check'                     => __( 'Recommended: Enabled. Keeps the plugin aligned with WooCommerce High-Performance Order Storage compatibility checks.', 'noesia-commerce-suite' ),
		);

		return $help[ $key ] ?? '';
	}

	/**
	 * Handles the related plugin operation.
	 */
	public function field_labels() {
		return array(
			'company_name'                   => __( 'Company / Store Name', 'noesia-commerce-suite' ), 'company_logo' => __( 'Company Logo', 'noesia-commerce-suite' ), 'primary_color' => __( 'Primary Color', 'noesia-commerce-suite' ), 'accent_color' => __( 'Accent Color', 'noesia-commerce-suite' ), 'button_style' => __( 'Button Style', 'noesia-commerce-suite' ), 'contact_text' => __( 'Contact Text', 'noesia-commerce-suite' ), 'support_email' => __( 'Support Email', 'noesia-commerce-suite' ), 'support_url' => __( 'Support Form URL', 'noesia-commerce-suite' ), 'phone_contact_text' => __( 'Phone / Contact Info', 'noesia-commerce-suite' ), 'show_woo_care_button' => __( 'Show Woo Care Button', 'noesia-commerce-suite' ),
			'enable_product_passport_qr'     => __( 'Enable Order Care Hub QR', 'noesia-commerce-suite' ), 'show_qr_thankyou' => __( 'Show QR on Thank You Page', 'noesia-commerce-suite' ), 'show_qr_emails' => __( 'Show Care Link in WooCommerce Emails', 'noesia-commerce-suite' ), 'show_qr_my_account' => __( 'Show QR in My Account', 'noesia-commerce-suite' ), 'show_qr_order_admin' => __( 'Show QR in Order Admin', 'noesia-commerce-suite' ), 'allow_printable_qr' => __( 'Allow Printable QR', 'noesia-commerce-suite' ), 'qr_size' => __( 'QR Size', 'noesia-commerce-suite' ), 'qr_foreground_color' => __( 'QR Foreground Color', 'noesia-commerce-suite' ), 'qr_background_color' => __( 'QR Background Color', 'noesia-commerce-suite' ), 'qr_label_text' => __( 'QR Label Text', 'noesia-commerce-suite' ), 'qr_card_layout_style' => __( 'QR Card Layout Style', 'noesia-commerce-suite' ), 'order_care_access_card_title' => __( 'Access Card Title', 'noesia-commerce-suite' ), 'order_care_access_card_text' => __( 'Access Card Text', 'noesia-commerce-suite' ), 'order_care_access_button_label' => __( 'Access Button Label', 'noesia-commerce-suite' ),
			'enable_care_page'               => __( 'Enable Order Care Hub', 'noesia-commerce-suite' ), 'require_login_care_page' => __( 'Require Customer Login', 'noesia-commerce-suite' ), 'privacy_noindex' => __( 'Noindex Hub Pages', 'noesia-commerce-suite' ), 'show_product_name' => __( 'Show Product Name', 'noesia-commerce-suite' ), 'show_order_number' => __( 'Show Order Number', 'noesia-commerce-suite' ), 'show_purchase_date' => __( 'Show Purchase Date', 'noesia-commerce-suite' ), 'show_warranty_status' => __( 'Show Legacy Warranty Status', 'noesia-commerce-suite' ), 'show_warranty_expiry_date' => __( 'Show Warranty Expiry Date', 'noesia-commerce-suite' ), 'show_verified_badge' => __( 'Show Verified Badge', 'noesia-commerce-suite' ), 'show_support_button' => __( 'Show Support Button', 'noesia-commerce-suite' ), 'show_review_button' => __( 'Show Review Button', 'noesia-commerce-suite' ), 'show_reorder_button' => __( 'Show Reorder Button', 'noesia-commerce-suite' ), 'show_store_contact' => __( 'Show Store Contact', 'noesia-commerce-suite' ), 'show_care_instructions' => __( 'Show Care Instructions', 'noesia-commerce-suite' ), 'care_page_title_text' => __( 'Hub Title Text', 'noesia-commerce-suite' ), 'care_page_intro_text' => __( 'Hub Intro Text', 'noesia-commerce-suite' ), 'care_instructions_text' => __( 'Care Instructions Text', 'noesia-commerce-suite' ),
			'default_warranty_months'        => __( 'Default Warranty Months', 'noesia-commerce-suite' ), 'show_verified_purchase_text' => __( 'Show Verified Purchase Text', 'noesia-commerce-suite' ), 'verified_purchase_text' => __( 'Verified Purchase Text', 'noesia-commerce-suite' ), 'warranty_active_text' => __( 'Warranty Active Text', 'noesia-commerce-suite' ), 'warranty_expired_text' => __( 'Warranty Expired Text', 'noesia-commerce-suite' ), 'warranty_unknown_text' => __( 'Warranty Unknown Text', 'noesia-commerce-suite' ), 'warranty_calculation_mode' => __( 'Warranty Calculation Mode', 'noesia-commerce-suite' ),
			'reorder_reminders_enabled'      => __( 'Enable Reorder Reminders', 'noesia-commerce-suite' ), 'reorder_default_days' => __( 'Default Reminder Days', 'noesia-commerce-suite' ), 'reorder_button_behavior' => __( 'Reorder Button Behavior', 'noesia-commerce-suite' ), 'reorder_email_enabled' => __( 'Enable Reorder Email', 'noesia-commerce-suite' ), 'reorder_batch_size' => __( 'Reminder Batch Size', 'noesia-commerce-suite' ), 'reorder_opt_out_enabled' => __( 'Enable Reminder Opt-out', 'noesia-commerce-suite' ), 'reorder_checkout_request_enabled' => __( 'Enable Checkout Reminder Request', 'noesia-commerce-suite' ), 'reorder_checkout_badge_label' => __( 'Checkout Badge Text', 'noesia-commerce-suite' ), 'reorder_checkout_label' => __( 'Checkout Checkbox Label', 'noesia-commerce-suite' ), 'reorder_checkout_info_text' => __( 'Checkout Info Text', 'noesia-commerce-suite' ), 'reorder_checkout_date_label' => __( 'Checkout Date Label', 'noesia-commerce-suite' ),
			'support_action_type'            => __( 'Support Button Action', 'noesia-commerce-suite' ), 'order_care_public_style' => __( 'Public Hub Style', 'noesia-commerce-suite' ), 'order_care_button_style' => __( 'Hub Button Style', 'noesia-commerce-suite' ), 'order_care_content_width' => __( 'Public Hub Width', 'noesia-commerce-suite' ),
			'order_care_warranty_enabled'    => __( 'Enable Warranty & Returns Link', 'noesia-commerce-suite' ), 'order_care_warranty_title' => __( 'Warranty & Returns Title', 'noesia-commerce-suite' ), 'order_care_warranty_text' => __( 'Warranty & Returns Text', 'noesia-commerce-suite' ), 'order_care_warranty_button_label' => __( 'Warranty & Returns Button Label', 'noesia-commerce-suite' ), 'order_care_warranty_url' => __( 'Warranty & Returns URL', 'noesia-commerce-suite' ),
			'order_care_documents_enabled'   => __( 'Enable Documents & Manuals Link', 'noesia-commerce-suite' ), 'order_care_documents_title' => __( 'Documents & Manuals Title', 'noesia-commerce-suite' ), 'order_care_documents_text' => __( 'Documents & Manuals Text', 'noesia-commerce-suite' ), 'order_care_documents_button_label' => __( 'Documents & Manuals Button Label', 'noesia-commerce-suite' ), 'order_care_documents_url' => __( 'Documents & Manuals URL', 'noesia-commerce-suite' ),
			'order_care_video_enabled'       => __( 'Enable Video Guides Link', 'noesia-commerce-suite' ), 'order_care_video_title' => __( 'Video Guides Title', 'noesia-commerce-suite' ), 'order_care_video_text' => __( 'Video Guides Text', 'noesia-commerce-suite' ), 'order_care_video_button_label' => __( 'Video Guides Button Label', 'noesia-commerce-suite' ), 'order_care_video_url' => __( 'Video Guides URL', 'noesia-commerce-suite' ),
			'order_care_promo_enabled'       => __( 'Enable Promo Block', 'noesia-commerce-suite' ), 'order_care_promo_title' => __( 'Promo Title', 'noesia-commerce-suite' ), 'order_care_promo_text' => __( 'Promo Text', 'noesia-commerce-suite' ), 'order_care_promo_code' => __( 'Promo Code', 'noesia-commerce-suite' ), 'order_care_promo_button_label' => __( 'Promo Button Label', 'noesia-commerce-suite' ), 'order_care_promo_url' => __( 'Promo URL', 'noesia-commerce-suite' ),
			'enable_support_block'           => __( 'Enable Support Block', 'noesia-commerce-suite' ), 'enable_review_block' => __( 'Enable Review Block', 'noesia-commerce-suite' ), 'google_review_url' => __( 'Google Review URL', 'noesia-commerce-suite' ), 'trustpilot_url' => __( 'Trustpilot URL', 'noesia-commerce-suite' ), 'store_review_url' => __( 'Store Review URL', 'noesia-commerce-suite' ), 'support_button_label' => __( 'Support Button Label', 'noesia-commerce-suite' ), 'review_button_label' => __( 'Review Button Label', 'noesia-commerce-suite' ), 'support_intro_text' => __( 'Support Intro Text', 'noesia-commerce-suite' ), 'review_intro_text' => __( 'Review Intro Text', 'noesia-commerce-suite' ), 'care_action_tracking_enabled' => __( 'Track Care Button Actions', 'noesia-commerce-suite' ),
			'analytics_default_range'        => __( 'Default Date Range', 'noesia-commerce-suite' ), 'show_analytics_revenue' => __( 'Show Revenue', 'noesia-commerce-suite' ), 'show_analytics_top_customers' => __( 'Show Top Customers', 'noesia-commerce-suite' ), 'show_analytics_top_cities' => __( 'Show Top Cities', 'noesia-commerce-suite' ), 'show_analytics_products' => __( 'Show Product Rankings', 'noesia-commerce-suite' ), 'show_analytics_categories' => __( 'Show Category Rankings', 'noesia-commerce-suite' ), 'analytics_cache_minutes' => __( 'Analytics Cache Minutes', 'noesia-commerce-suite' ),
			'dashboard_weather_enabled'      => __( 'Enable Dashboard Weather', 'noesia-commerce-suite' ), 'dashboard_weather_location_label' => __( 'Weather Location Label', 'noesia-commerce-suite' ), 'dashboard_weather_location_search' => __( 'Weather Location Search', 'noesia-commerce-suite' ), 'dashboard_weather_latitude' => __( 'Weather Latitude', 'noesia-commerce-suite' ), 'dashboard_weather_longitude' => __( 'Weather Longitude', 'noesia-commerce-suite' ), 'dashboard_weather_cache_minutes' => __( 'Weather Cache Minutes', 'noesia-commerce-suite' ),
			'enable_impact_map_shortcode'    => __( 'Enable Impact Map Shortcode', 'noesia-commerce-suite' ), 'impact_map_cache_enabled' => __( 'Use Cached Snapshot', 'noesia-commerce-suite' ), 'impact_map_style' => __( 'Public Display Style', 'noesia-commerce-suite' ), 'impact_map_background_size' => __( 'Public Block Size', 'noesia-commerce-suite' ), 'impact_map_max_visible_areas' => __( 'Maximum Visible Areas', 'noesia-commerce-suite' ), 'impact_map_public_eyebrow' => __( 'Public Eyebrow Label', 'noesia-commerce-suite' ), 'impact_map_public_title' => __( 'Public Title', 'noesia-commerce-suite' ), 'impact_map_public_subtitle' => __( 'Public Subtitle', 'noesia-commerce-suite' ), 'impact_map_threshold' => __( 'Minimum Privacy Threshold', 'noesia-commerce-suite' ), 'impact_snapshot_order_limit' => __( 'Snapshot Order Limit', 'noesia-commerce-suite' ), 'impact_map_group_by' => __( 'Group By', 'noesia-commerce-suite' ), 'impact_map_show_orders' => __( 'Show Orders Count', 'noesia-commerce-suite' ), 'impact_map_show_products' => __( 'Show Products Count', 'noesia-commerce-suite' ), 'impact_map_show_top_categories' => __( 'Show Top Categories', 'noesia-commerce-suite' ), 'impact_map_show_top_products' => __( 'Show Top Products', 'noesia-commerce-suite' ), 'impact_map_show_revenue' => __( 'Show Revenue Publicly', 'noesia-commerce-suite' ),
			'enable_doctor_scan'             => __( 'Enable Product Scan', 'noesia-commerce-suite' ), 'doctor_scan_without_image' => __( 'Scan Products Without Image', 'noesia-commerce-suite' ), 'doctor_scan_without_price' => __( 'Scan Products Without Price', 'noesia-commerce-suite' ), 'doctor_scan_without_sku' => __( 'Scan Products Without SKU', 'noesia-commerce-suite' ), 'doctor_scan_without_category' => __( 'Scan Products Without Category', 'noesia-commerce-suite' ), 'doctor_scan_short_description' => __( 'Scan Short Descriptions', 'noesia-commerce-suite' ), 'doctor_scan_large_images' => __( 'Scan Large Images', 'noesia-commerce-suite' ), 'doctor_scan_missing_alt' => __( 'Scan Missing Alt Text', 'noesia-commerce-suite' ), 'doctor_scan_missing_shipping_data' => __( 'Scan Missing Shipping Data', 'noesia-commerce-suite' ), 'doctor_scan_missing_related_products' => __( 'Scan Missing Cross-sells / Upsells', 'noesia-commerce-suite' ), 'doctor_scan_hidden_in_stock' => __( 'Scan Hidden In-stock Products', 'noesia-commerce-suite' ), 'doctor_scan_visible_out_of_stock' => __( 'Scan Visible Out-of-stock Products', 'noesia-commerce-suite' ), 'doctor_scan_suspicious_order_signals' => __( 'Scan Suspicious Order Signals', 'noesia-commerce-suite' ), 'doctor_scan_data_retention_review' => __( 'Scan Data Retention Review Items', 'noesia-commerce-suite' ), 'doctor_data_retention_months' => __( 'Data Retention Review Months', 'noesia-commerce-suite' ), 'doctor_scan_temporary_data' => __( 'Scan WooCommerce Temporary Data', 'noesia-commerce-suite' ), 'doctor_scan_autoloaded_options' => __( 'Scan Autoloaded Options Health', 'noesia-commerce-suite' ), 'doctor_scan_action_scheduler_queue' => __( 'Scan WooCommerce Background Tasks', 'noesia-commerce-suite' ), 'doctor_scan_broken_links' => __( 'Scan Broken Links / 404', 'noesia-commerce-suite' ), 'doctor_broken_link_limit' => __( 'Broken Link URL Scope', 'noesia-commerce-suite' ), 'doctor_check_wc_pages' => __( 'Check WooCommerce Pages', 'noesia-commerce-suite' ), 'doctor_product_scan_limit' => __( 'Product Scan Scope', 'noesia-commerce-suite' ), 'doctor_large_image_kb' => __( 'Large Image Threshold KB', 'noesia-commerce-suite' ), 'doctor_result_retention_days' => __( 'Scan Result Retention Days', 'noesia-commerce-suite' ), 'doctor_severity_threshold' => __( 'Severity Threshold', 'noesia-commerce-suite' ),
			'passport_email_enabled'         => __( 'Order Care Email Enabled', 'noesia-commerce-suite' ), 'email_logo' => __( 'Email Logo URL', 'noesia-commerce-suite' ), 'email_button_color' => __( 'Email Button Color', 'noesia-commerce-suite' ), 'email_sender_name' => __( 'Email Sender Name', 'noesia-commerce-suite' ), 'test_email_recipient' => __( 'Verification Email Recipient', 'noesia-commerce-suite' ), 'passport_email_subject' => __( 'Order Care Hub Email Subject', 'noesia-commerce-suite' ), 'passport_email_body' => __( 'Order Care Hub Email Body', 'noesia-commerce-suite' ), 'passport_email_button_label' => __( 'Order Care Hub Button Label', 'noesia-commerce-suite' ), 'reorder_checkout_style' => __( 'Checkout Box Style', 'noesia-commerce-suite' ), 'reorder_email_subject' => __( 'Reorder Email Subject', 'noesia-commerce-suite' ), 'reorder_email_body' => __( 'Reorder Email Body', 'noesia-commerce-suite' ), 'reorder_email_button_label' => __( 'Reorder Button Label', 'noesia-commerce-suite' ), 'unsubscribe_text' => __( 'Unsubscribe Text', 'noesia-commerce-suite' ), 'email_footer_text' => __( 'Email Footer Text', 'noesia-commerce-suite' ), 'email_log_retention_days' => __( 'Keep Email History For', 'noesia-commerce-suite' ),
			'privacy_hide_full_name'         => __( 'Hide Full Name Publicly', 'noesia-commerce-suite' ), 'privacy_hide_address' => __( 'Hide Address Publicly', 'noesia-commerce-suite' ), 'privacy_hide_email' => __( 'Hide Email Publicly', 'noesia-commerce-suite' ), 'privacy_hide_phone' => __( 'Hide Phone Publicly', 'noesia-commerce-suite' ), 'privacy_hide_revenue_public' => __( 'Hide Revenue Publicly by Default', 'noesia-commerce-suite' ), 'secure_token_behavior' => __( 'Secure Token Behavior', 'noesia-commerce-suite' ), 'logs_retention_days' => __( 'Activity History Retention Days', 'noesia-commerce-suite' ), 'delete_data_on_uninstall' => __( 'Remove Noesia Data on Uninstall', 'noesia-commerce-suite' ),
			'wc_status_check'                => __( 'WooCommerce Status Check', 'noesia-commerce-suite' ), 'hpos_status_check' => __( 'HPOS Compatibility Status', 'noesia-commerce-suite' ), 'my_account_integration' => __( 'My Account Integration', 'noesia-commerce-suite' ), 'thankyou_integration' => __( 'Thank You Page Integration', 'noesia-commerce-suite' ), 'email_integration' => __( 'Email Integration', 'noesia-commerce-suite' ), 'order_admin_metabox' => __( 'Order Admin Metabox', 'noesia-commerce-suite' ),
		);
	}

	/**
	 * Handles the related plugin operation.
	 */
	public function get_latest_order_summary() {
		$empty = array(
			'has_order'  => false,
			'label'      => __( 'Last order: none yet', 'noesia-commerce-suite' ),
			'aria'       => __( 'No WooCommerce orders found yet.', 'noesia-commerce-suite' ),
			'url'        => $this->tab_url( 'intelligence-analytics' ),
		);

		if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'wc_get_orders' ) ) {
			$empty['label']  = __( 'Last order: Woo unavailable', 'noesia-commerce-suite' );
			$empty['aria']   = __( 'WooCommerce is not available.', 'noesia-commerce-suite' );
			return $empty;
		}

		$orders = wc_get_orders(
			array(
				'limit'    => 1,
				'orderby'  => 'date',
				'order'    => 'DESC',
				'return'   => 'objects',
			)
		);

		if ( empty( $orders ) || ! is_a( $orders[0], 'WC_Order' ) ) {
			return $empty;
		}

		$order        = $orders[0];
		$order_number = $order->get_order_number();
		$total        = function_exists( 'wc_price' ) ? wp_strip_all_tags( wc_price( (float) $order->get_total(), array( 'currency' => $order->get_currency() ) ) ) : html_entity_decode( get_woocommerce_currency_symbol( $order->get_currency() ) ) . number_format_i18n( (float) $order->get_total(), 2 );
		$label        = sprintf(
			/* translators: 1: order number, 2: order total. */
			__( 'Last order: #%1$s · %2$s', 'noesia-commerce-suite' ),
			$order_number,
			$total
		);

		$url = method_exists( $order, 'get_edit_order_url' ) ? $order->get_edit_order_url() : $this->tab_url( 'intelligence-analytics' );

		return array(
			'has_order'  => true,
			'label'      => $label,
			'aria'       => sprintf(
				/* translators: 1: order number, 2: order total. */
				__( 'Open latest order #%1$s. Total: %2$s', 'noesia-commerce-suite' ),
				$order_number,
				$total
			),
			'url'       => $url,
		);
	}

	/**
	 * Handles the related plugin operation.
	 */
	public function get_last_hour_order_count() {
		if ( ! function_exists( 'wc_get_orders' ) ) {
			return 0;
		}

		$threshold = time() - HOUR_IN_SECONDS;

		try {
			$query = wc_get_orders(
				array(
					'limit'         => 1,
					'paginate'      => true,
					'return'        => 'ids',
					'type'          => 'shop_order',
					'status'        => array_keys( wc_get_order_statuses() ),
					'date_created'  => '>=' . $threshold,
				)
			);

			if ( is_object( $query ) && isset( $query->total ) ) {
				return absint( $query->total );
			}

			if ( is_array( $query ) ) {
				return count( $query );
			}
		} catch ( Exception $e ) {
			return 0;
		}

		return 0;
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $tab Tab.
	 */
	public function icon_for_tab( $tab ) {
		$icon = '•';

		if ( $this->module_registry ) {
			$module_icon = $this->module_registry->icon( $tab );
			$icon        = $module_icon ? $module_icon : '•';
		}

		return apply_filters( 'noesia_cs_admin_tab_icon', $icon, $tab );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $tab Tab.
	 */
	public function headline_for_tab( $tab ) {
		$label = __( 'Dashboard', 'noesia-commerce-suite' );

		if ( $this->module_registry ) {
			$module_label = $this->module_registry->label( $tab );
			$label        = $module_label ? $module_label : $label;
		}

		return apply_filters( 'noesia_cs_admin_tab_label', $label, $tab );
	}

	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $tab Tab.
	 */
	public function subtitle_for_tab( $tab ) {
		$subtitle = $this->module_registry ? $this->module_registry->description( $tab ) : '';

		return apply_filters( 'noesia_cs_admin_tab_subtitle', $subtitle, $tab );
	}
	/**
	 * Handles the related plugin operation.
	 *
	 * @param mixed $notice Notice.
	 */
	public function notice_text( $notice ) {
		$notices = array(
		'saved'                  => __( 'Settings saved.', 'noesia-commerce-suite' ),
		'scan-complete'          => __( 'Manual Ecommerce Doctor scan completed.', 'noesia-commerce-suite' ),
		'impact-refreshed'       => __( 'Impact Map cached snapshot refreshed.', 'noesia-commerce-suite' ),
		'analytics-refreshed'    => __( 'Analytics cache refreshed.', 'noesia-commerce-suite' ),
		'email-sent'             => __( 'Verification email sent.', 'noesia-commerce-suite' ),
		'email-failed'           => __( 'Verification email could not be sent by this server.', 'noesia-commerce-suite' ),
		'reorder-built'          => __( 'Reorder reminder history refreshed from eligible WooCommerce orders.', 'noesia-commerce-suite' ),
		'reorder-test-sent'      => __( 'Test reminder email sent. Check the inbox you selected.', 'noesia-commerce-suite' ),
		'reorder-test-failed'    => __( 'The test reminder email could not be sent. Check that WooCommerce has at least one recent order and that this site can send mail.', 'noesia-commerce-suite' ),
		'cleanup-complete'       => __( 'Operational data cleanup completed.', 'noesia-commerce-suite' ),
		'rewrites-refreshed'     => __( 'Care endpoint rewrite rules refreshed.', 'noesia-commerce-suite' ),
	); return $notices[ $notice ] ?? __( 'Done.', 'noesia-commerce-suite' ); }
}
