<?php
/**
 * Product Sync View
 *
 * This class handles the UI for product synchronization.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/views/src/common/pages/supplier/sync
 * @author     miniOrange
 * @license    Expat
 * @link       https://miniorange.com
 */

declare(strict_types=1);

namespace MOMCS_Sync\Views\Src\Common\Pages\Supplier\Sync;

use MOMCS_Sync\Views\Src\Common\Components\Header_View;
use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Common\Utils\Utils;
use MOMCS_Sync\Includes\Common\Utils\Asin_Helper;
use MOMCS_Sync\Includes\Common\Handlers\Listing_Status_Handler;
use MOMCS_Sync\Includes\Plans\Premium\Utils\Marketplace_Display_Helper;

/**
 * Class Product_Sync_View
 *
 * Handles the UI for product synchronization
 */
class Product_Sync_View {

	/**
	 * Render the product sync page
	 */
	public function render() {
		$this->enqueue_scripts();
		// Get current page and items per page.
		$current_page   = (int) Utils::get_current_page_parameter_value( 'paged', '1' );
		$items_per_page = $this->get_items_per_page();

		// Get products with pagination.
		$products       = $this->get_products( $current_page, $items_per_page );
		$total_products = $this->get_total_products_count();

		// Calculate total pages.
		$total_pages = (int) ceil( $total_products / $items_per_page );

		// Get sync status.
		$sync_status = $this->get_sync_status();

		// Render the page.
		$this->render_page( $products, $sync_status, $current_page, $total_pages, $total_products );
	}

	/**
	 * Enqueue scripts and styles
	 */
	private function enqueue_scripts() {
		// Core admin styles.
		wp_enqueue_style( 'momcs-sync-admin-style', MOMCS_PLUGIN_URL . 'assets/css/admin-style.css', array(), MOMCS_VERSION );
		wp_enqueue_style( 'momcs-sync-admin-components', MOMCS_PLUGIN_URL . 'assets/css/admin.css', array( 'momcs-sync-admin-style' ), MOMCS_VERSION );

		// Modern product list styles - loaded after admin styles to override.
		wp_enqueue_style( 'momcs-sync-product-list-modern', MOMCS_PLUGIN_URL . 'assets/css/product-list-modern.css', array( 'momcs-sync-admin-components' ), MOMCS_VERSION );

		// Queue styles.
		wp_enqueue_style( 'momcs-sync-queue', MOMCS_PLUGIN_URL . 'assets/css/sync-queue.css', array( 'momcs-sync-product-list-modern' ), MOMCS_VERSION );

		// Core admin scripts.
		wp_enqueue_script( 'momcs-sync-admin-script', MOMCS_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery' ), MOMCS_VERSION, true );
		wp_enqueue_script( 'momcs-sync-product-sync', MOMCS_PLUGIN_URL . 'assets/js/product-sync.js', array( 'jquery' ), MOMCS_VERSION, true );

		// Modern product search and UI interactions.
		wp_enqueue_script( 'momcs-sync-product-search', MOMCS_PLUGIN_URL . 'assets/js/product-search.js', array( 'jquery', 'momcs-sync-product-sync' ), MOMCS_VERSION, true );

		// Localize scripts with data.
		wp_localize_script(
			'momcs-sync-product-sync',
			'momcs_sync',
			array(
				'ajax_url'         => admin_url( 'admin-ajax.php' ),
				'nonce'            => wp_create_nonce( Plugin_Constants::NONCE_MAIN ),
				'is_premium'       => Utils::is_premium_plan(),
				'marketplace_info' => $this->get_marketplace_info_for_js(),
				'strings'          => array(
					'sync_success'      => esc_html__( 'Product synchronized successfully', 'multi-channel-for-woocommerce' ),
					'sync_error'        => esc_html__( 'Error synchronizing product', 'multi-channel-for-woocommerce' ),
					'bulk_sync_success' => esc_html__( 'Products synchronized successfully', 'multi-channel-for-woocommerce' ),
					'bulk_sync_error'   => esc_html__( 'Error synchronizing products', 'multi-channel-for-woocommerce' ),
					'confirm_bulk_sync' => esc_html__( 'Are you sure you want to synchronize the selected products?', 'multi-channel-for-woocommerce' ),
					'no_products'       => esc_html__( 'Please select at least one product', 'multi-channel-for-woocommerce' ),
					'no_action'         => esc_html__( 'Please select an action', 'multi-channel-for-woocommerce' ),
					'syncing'           => esc_html__( 'Syncing...', 'multi-channel-for-woocommerce' ),
					'search_no_results' => esc_html__( 'No products found', 'multi-channel-for-woocommerce' ),
				),
			)
		);
	}

	/**
	 * Get marketplace info map for JavaScript.
	 *
	 * Returns array of marketplace_id => { name, flag } for tooltip rendering
	 * in the refresh status JavaScript handler.
	 *
	 * @return array<string, array<string, string>> Marketplace info keyed by ID.
	 */
	private function get_marketplace_info_for_js(): array {
		if ( ! Utils::is_premium_plan() ) {
			return array();
		}

		$info             = array();
		$all_marketplaces = Marketplace_Display_Helper::get_all_marketplace_info();

		foreach ( $all_marketplaces as $mp_id => $mp_data ) {
			$info[ $mp_id ] = array(
				'name' => $mp_data['name'],
				'flag' => $mp_data['flag'],
			);
		}

		return $info;
	}

	/**
	 * Get items per page from user meta or default.
	 *
	 * @return int Number of items per page.
	 */
	private function get_items_per_page(): int {
		$user_id  = get_current_user_id();
		$per_page = get_user_meta( $user_id, 'momcs_products_per_page', true );
		return $per_page ? (int) $per_page : 10;
	}

	/**
	 * Get total count of products with applied filters.
	 *
	 * @return int Total products count.
	 */
	private function get_total_products_count(): int {
		// Build base tax_query for product types.
		$tax_query = array(
			array(
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => array( 'simple', 'variable' ),
				'operator' => 'IN',
			),
		);

		// Handle category filter.
		$category_filter = Utils::get_current_page_parameter_value( 'product_cat', '' );
		if ( ! empty( $category_filter ) ) {
			$tax_query['relation'] = 'AND';
			$tax_query[]           = array(
				'taxonomy' => 'product_cat',
				'field'    => 'term_id',
				'terms'    => absint( $category_filter ),
			);
		}

		$args = array(
			'post_type'      => 'product',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'fields'         => 'ids',
			'tax_query'      => $tax_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
		);

		// Handle status filter.
		$status_filter = Utils::get_current_page_parameter_value( 'listing_status', '' );
		if ( ! empty( $status_filter ) ) {
			if ( 'not_uploaded' === $status_filter ) {
				$args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					'relation' => 'OR',
					array(
						'key'     => '_momcs_amz_listing_status',
						'compare' => 'NOT EXISTS',
					),
					array(
						'key'     => '_momcs_amz_listing_status',
						'value'   => '',
						'compare' => '=',
					),
				);
			} else {
				$args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					array(
						'key'     => '_momcs_amz_listing_status',
						'value'   => $status_filter,
						'compare' => '=',
					),
				);
			}
		}

		$query = new \WP_Query( $args );
		return $query->found_posts;
	}

	/**
	 * Get WooCommerce products with pagination and sorting.
	 *
	 * @param int $current_page   Current page number.
	 * @param int $items_per_page Number of items per page.
	 * @return array Products.
	 */
	private function get_products( int $current_page = 1, int $items_per_page = 10 ): array {
		// Build base tax_query for product types.
		$tax_query = array(
			array(
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => array( 'simple', 'variable' ),
				'operator' => 'IN',
			),
		);

		// Handle category filter.
		$category_filter = Utils::get_current_page_parameter_value( 'product_cat', '' );
		if ( ! empty( $category_filter ) ) {
			$tax_query['relation'] = 'AND';
			$tax_query[]           = array(
				'taxonomy' => 'product_cat',
				'field'    => 'term_id',
				'terms'    => absint( $category_filter ),
			);
		}

		$args = array(
			'post_type'      => 'product',
			'posts_per_page' => $items_per_page,
			'post_status'    => 'publish',
			'paged'          => $current_page,
			'tax_query'      => $tax_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
		);

		// Handle sorting.
		$orderby = Utils::get_current_page_parameter_value( 'orderby', 'date-desc' );
		switch ( $orderby ) {
			case 'date-asc':
				$args['orderby'] = 'date';
				$args['order']   = 'ASC';
				break;
			case 'name-asc':
				$args['orderby'] = 'title';
				$args['order']   = 'ASC';
				break;
			case 'name-desc':
				$args['orderby'] = 'title';
				$args['order']   = 'DESC';
				break;
			case 'price-asc':
				$args['meta_key'] = '_price'; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
				$args['orderby']  = 'meta_value_num';
				$args['order']    = 'ASC';
				break;
			case 'price-desc':
				$args['meta_key'] = '_price'; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
				$args['orderby']  = 'meta_value_num';
				$args['order']    = 'DESC';
				break;
			case 'date-desc':
			default:
				$args['orderby'] = 'date';
				$args['order']   = 'DESC';
				break;
		}

		// Handle status filter.
		$status_filter = Utils::get_current_page_parameter_value( 'listing_status', '' );
		if ( ! empty( $status_filter ) ) {
			if ( 'not_uploaded' === $status_filter ) {
				$args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					'relation' => 'OR',
					array(
						'key'     => '_momcs_amz_listing_status',
						'compare' => 'NOT EXISTS',
					),
					array(
						'key'     => '_momcs_amz_listing_status',
						'value'   => '',
						'compare' => '=',
					),
				);
			} else {
				$args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
					array(
						'key'     => '_momcs_amz_listing_status',
						'value'   => $status_filter,
						'compare' => '=',
					),
				);
			}
		}

		$products_query = new \WP_Query( $args );
		$products       = array();
		$product_ids    = array();

		// First pass: collect product IDs for cache warming.
		if ( $products_query->have_posts() ) {
			while ( $products_query->have_posts() ) {
				$products_query->the_post();
				$product_ids[] = get_the_ID();
			}
			$products_query->rewind_posts();
		}

		// Warm the marketplace data cache for all products at once (premium only).
		if ( ! empty( $product_ids ) && Utils::is_premium_plan() ) {
			Asin_Helper::warm_cache_for_products( $product_ids );
		}

		if ( $products_query->have_posts() ) {
			while ( $products_query->have_posts() ) {
				$products_query->the_post();
				$product = wc_get_product( get_the_ID() );

				if ( ! $product instanceof \WC_Product ) {
					continue;
				}

				$product_type = $product->get_type();

				// Guard against unexpected product types.
				if ( ! in_array( $product_type, array( 'simple', 'variable' ), true ) ) {
					continue;
				}

				$product_type_labels = wc_get_product_types();
				$type_label          = isset( $product_type_labels[ $product_type ] ) ? $product_type_labels[ $product_type ] : ucfirst( $product_type );

				// Get product categories.
				$categories = array();
				$terms      = get_the_terms( $product->get_id(), 'product_cat' );
				if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
					foreach ( $terms as $term ) {
						$categories[] = $term->name;
					}
				}

				// Fetch Amazon-specific meta values.
				$amz_id_value = get_post_meta( $product->get_id(), '_momcs_amz_id_value', true );
				$asin         = Asin_Helper::get_product_asin( $product->get_id() );

				// Fetch listing status & issues from meta (legacy single-status).
				$listing_status = get_post_meta( $product->get_id(), '_momcs_amz_listing_status', true );
				$has_issues     = Listing_Status_Handler::product_has_issues( $product->get_id() );

				// Fetch per-marketplace data for status chips (premium only).
				$marketplace_statuses = array();
				if ( Utils::is_premium_plan() ) {
					$marketplace_statuses = Asin_Helper::get_all_marketplace_data( $product->get_id() );
					// Option A: set single asin from first marketplace with ASIN for "View on Amazon" link.
					foreach ( $marketplace_statuses as $mp_data ) {
						if ( ! empty( $mp_data['asin'] ) ) {
							$asin = $mp_data['asin'];
							break;
						}
					}
					// For variable products, aggregate Amazon price range from variations (stored on variation meta).
					if ( 'variable' === $product_type ) {
						$marketplace_statuses = $this->merge_variable_amazon_price_ranges( $product->get_id(), $marketplace_statuses );
					}
				}

				// WooCommerce price: use price range for variable products (like WC product list).
				$formatted_price = 'variable' === $product_type
					? $product->get_price_html()
					: wc_price( $product->get_price() );

				$products[] = array(
					'id'                   => $product->get_id(),
					'name'                 => $product->get_name(),
					'sku'                  => $product->get_sku(),
					'price'                => $product->get_price(),
					'formatted_price'      => $formatted_price,
					'stock_status'         => $product->get_stock_status(),
					'image'                => get_the_post_thumbnail_url( $product->get_id(), 'thumbnail' ),
					'categories'           => implode( ', ', $categories ),
					'type'                 => $product_type,
					'type_label'           => $type_label,
					'has_amz_id'           => ! empty( $amz_id_value ),
					'asin'                 => $asin,
					'listing_status'       => $listing_status,
					'has_issues'           => $has_issues,
					'marketplace_statuses' => $marketplace_statuses,
				);
			}
			wp_reset_postdata();
		}

		return $products;
	}

	/**
	 * Merge Amazon price range from variations into parent marketplace statuses.
	 *
	 * Variable products store _momcs_amz_price_{marketplace_id} on variations.
	 * This method aggregates min/max per marketplace so the Product tab can show a price range.
	 *
	 * @param int                 $parent_id            Variable product (parent) post ID.
	 * @param array<string,array> $marketplace_statuses Parent marketplace data (asin, status, price, condition).
	 * @return array<string,array> Marketplace statuses with price_min/price_max (and price when min=max) added per marketplace.
	 */
	private function merge_variable_amazon_price_ranges( int $parent_id, array $marketplace_statuses ): array {
		$product = wc_get_product( $parent_id );
		if ( ! $product || ! $product->is_type( 'variable' ) ) {
			return $marketplace_statuses;
		}

		// Seed with parent's Amazon price (import/sync may set price on parent only).
		$by_mp = array();
		foreach ( $marketplace_statuses as $mp_id => $data ) {
			if ( isset( $data['price'] ) && is_numeric( $data['price'] ) ) {
				$by_mp[ $mp_id ] = array( (float) $data['price'] );
			}
		}

		$variation_ids = $product->get_children();
		if ( ! empty( $variation_ids ) ) {
			global $wpdb;
			$meta_prefix = '_momcs_amz_price_';
			$query       = $wpdb->prepare(
				"SELECT meta_key, meta_value FROM {$wpdb->postmeta}
				WHERE post_id IN (" . implode( ',', array_fill( 0, count( $variation_ids ), '%d' ) ) . ")
				AND meta_key LIKE %s
				AND meta_value != ''",
				array_merge( $variation_ids, array( $meta_prefix . '%' ) )
			);
			$rows = $wpdb->get_results( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
			if ( ! empty( $rows ) && is_array( $rows ) ) {
				$prefix_len = strlen( $meta_prefix );
				foreach ( $rows as $row ) {
					$marketplace_id = substr( $row['meta_key'], $prefix_len );
					if ( '' === $marketplace_id ) {
						continue;
					}
					$price = (float) $row['meta_value'];
					if ( ! isset( $by_mp[ $marketplace_id ] ) ) {
						$by_mp[ $marketplace_id ] = array();
					}
					$by_mp[ $marketplace_id ][] = $price;
				}
			}
		}

		foreach ( $by_mp as $mp_id => $prices ) {
			$min = min( $prices );
			$max = max( $prices );
			if ( ! isset( $marketplace_statuses[ $mp_id ] ) ) {
				$marketplace_statuses[ $mp_id ] = array(
					'asin'      => null,
					'status'    => null,
					'price'     => null,
					'condition' => null,
				);
			}
			$marketplace_statuses[ $mp_id ]['price_min'] = $min;
			$marketplace_statuses[ $mp_id ]['price_max'] = $max;
			if ( $min === $max ) {
				$marketplace_statuses[ $mp_id ]['price'] = $min;
			}
		}

		return $marketplace_statuses;
	}

	/**
	 * Get sync status for products.
	 *
	 * @return array Sync status.
	 */
	private function get_sync_status(): array {

		$sync_status = array();

		$meta_query = array(
			'post_type'      => 'product',
			'posts_per_page' => -1,
			'meta_query'     => array( //phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required to get products with ASIN.
				array(
					'key'     => '_momcs_asin',
					'compare' => 'EXISTS',
				),
			),
			'fields'         => 'ids',
		);

		$products_with_asin = get_posts( $meta_query );

		if ( ! empty( $products_with_asin ) ) {
			foreach ( $products_with_asin as $product_id ) {
				$asin = get_post_meta( $product_id, '_momcs_asin', true );

				if ( ! isset( $sync_status[ $product_id ] ) || empty( $sync_status[ $product_id ]['amazon_product_id'] ) ) {
					$sync_date = get_post_meta( $product_id, '_momcs_sync_date', true );
					if ( empty( $sync_date ) ) {
						$sync_date = current_time( 'mysql' );
					}

					$sync_status[ $product_id ] = array(
						'amazon_product_id' => $asin,
						'synced_at'         => $sync_date,
						'source'            => 'meta',
					);
				}
			}
		}

		return $sync_status;
	}

	/**
	 * Render the page
	 *
	 * @param array $products       Products.
	 * @param array $sync_status    Sync status.
	 * @param int   $current_page   Current page number.
	 * @param int   $total_pages    Total number of pages.
	 * @param int   $total_products Total number of products.
	 */
	private function render_page( array $products, array $sync_status, int $current_page = 1, int $total_pages = 1, int $total_products = 0 ) {
		$items_per_page = $this->get_items_per_page();
		$start_item     = ( $current_page - 1 ) * $items_per_page + 1;
		$end_item       = min( $current_page * $items_per_page, $total_products );

		// Get all product categories for filter dropdown.
		$categories = get_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => true,
			)
		);
		?>
		<div class="wrap momcs-sync-container">
			<h1 class="screen-reader-text"><?php esc_html_e( 'Multi-channel for WooCommerce', 'multi-channel-for-woocommerce' ); ?></h1>
			<?php ( new Header_View( 'products' ) )->render(); ?>

			<div class="momcs-products-modern">
				<?php
				// Amazon Product Sync progress container (initially hidden).
				if ( Utils::is_premium_plan() ) {
					?>
					<div id="momcs-product-sync-progress" class="momcs-sync-progress-container momcs-product-sync-progress" style="display: none;"></div>
					<?php
				}
				?>

				<!-- Modern Page Header -->
				<div class="momcs-products-header">
					<div class="momcs-products-header-left">
						<h2 class="momcs-products-title"><?php esc_html_e( 'Products', 'multi-channel-for-woocommerce' ); ?></h2>
						<span class="momcs-products-count"><?php echo esc_html( number_format_i18n( $total_products ) ); ?> <?php esc_html_e( 'items', 'multi-channel-for-woocommerce' ); ?></span>
						<a href="<?php echo esc_url( apply_filters( 'momcs_product_sync_video_guide_url', 'https://www.youtube.com/watch?v=VIDEO_ID_HERE' ) ); ?>" target="_blank" rel="noopener noreferrer" class="momcs-video-guide-btn" title="<?php esc_attr_e( 'Watch a quick video guide on how to list products on Amazon', 'multi-channel-for-woocommerce' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
								<circle cx="12" cy="12" r="10"/>
								<polygon points="10 8 16 12 10 16 10 8"/>
							</svg>
							<?php esc_html_e( 'Video guide', 'multi-channel-for-woocommerce' ); ?>
						</a>
					</div>
				</div>

				<!-- Info Notice -->
				<div class="momcs-products-notice">
					<svg class="momcs-products-notice-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
						<circle cx="12" cy="12" r="10"></circle>
						<path d="M12 16v-4"></path>
						<path d="M12 8h.01"></path>
					</svg>
					<p><span class="momcs-text-accent-orange"><?php esc_html_e( 'Select products and apply an action to list or unlist them on Amazon marketplace.', 'multi-channel-for-woocommerce' ); ?></span></p>
				</div>

				<!-- Combined Filter and Actions Bar -->
				<?php
				$current_orderby  = Utils::get_current_page_parameter_value( 'orderby', 'date-desc' );
				$current_category = Utils::get_current_page_parameter_value( 'product_cat', '' );
				$current_status   = Utils::get_current_page_parameter_value( 'listing_status', '' );
				?>
				<div class="momcs-products-toolbar">
					<!-- Left: Search only (outside filters) -->
					<div class="momcs-toolbar-left">
						<div class="momcs-product-search-wrapper">
							<svg class="momcs-product-search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
								<circle cx="11" cy="11" r="8"></circle>
								<path d="m21 21-4.35-4.35"></path>
							</svg>
							<input type="text" class="momcs-product-search-input" id="momcs-product-search" placeholder="<?php esc_attr_e( 'Search products...', 'multi-channel-for-woocommerce' ); ?>" autocomplete="off">
							<div class="momcs-product-search-dropdown" id="momcs-search-dropdown"></div>
						</div>
					</div>

					<!-- Right: Filters + Actions + Apply + Sync (grouped together) -->
					<div class="momcs-toolbar-right">
						<button type="button" class="momcs-filters-trigger-btn" id="momcs-filters-trigger" aria-haspopup="dialog" aria-expanded="false">
							<svg class="momcs-filters-trigger-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
								<line x1="4" y1="21" x2="4" y2="14"></line>
								<line x1="4" y1="10" x2="4" y2="3"></line>
								<line x1="12" y1="21" x2="12" y2="12"></line>
								<line x1="12" y1="8" x2="12" y2="3"></line>
								<line x1="20" y1="21" x2="20" y2="16"></line>
								<line x1="20" y1="12" x2="20" y2="3"></line>
								<line x1="1" y1="14" x2="7" y2="14"></line>
								<line x1="9" y1="8" x2="15" y2="8"></line>
								<line x1="17" y1="16" x2="23" y2="16"></line>
							</svg>
							<span class="momcs-filters-trigger-text"><?php esc_html_e( 'Filters', 'multi-channel-for-woocommerce' ); ?></span>
						</button>
						<div class="momcs-action-dropdown">
							<span class="momcs-action-label"><?php esc_html_e( 'Actions', 'multi-channel-for-woocommerce' ); ?></span>
							<select class="momcs-bulk-select" id="momcs-sync-list-action">
								<option value=""><?php esc_html_e( 'Select', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="list"><?php esc_html_e( 'List on Amazon', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="unlist"><?php esc_html_e( 'Unlist from Amazon', 'multi-channel-for-woocommerce' ); ?></option>
							</select>
						</div>
						<button type="button" class="momcs-bulk-apply-btn" id="momcs-sync-apply-action">
							<?php esc_html_e( 'Apply', 'multi-channel-for-woocommerce' ); ?>
						</button>
						<?php if ( Utils::is_premium_plan() ) : ?>
							<button type="button" class="momcs-sync-amazon-btn" id="momcs-sync-from-amazon-btn">
								<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-cloud-sync-icon lucide-cloud-sync">
									<path d="m17 18-1.535 1.605a5 5 0 0 1-8-1.5"/>
									<path d="M17 22v-4h-4"/>
									<path d="M20.996 15.251A4.5 4.5 0 0 0 17.495 8h-1.79a7 7 0 1 0-12.709 5.607"/>
									<path d="M7 10v4h4"/>
									<path d="m7 14 1.535-1.605a5 5 0 0 1 8 1.5"/>
								</svg>
								<?php esc_html_e( 'Sync from Amazon', 'multi-channel-for-woocommerce' ); ?>
							</button>
						<?php else : ?>
							<button type="button" class="momcs-sync-amazon-btn momcs-sync-amazon-btn--locked" id="momcs-sync-from-amazon-btn" disabled title="<?php esc_attr_e( 'Upgrade to Premium to sync products from Amazon', 'multi-channel-for-woocommerce' ); ?>">
								<span class="dashicons dashicons-lock momcs-sync-amazon-lock" aria-hidden="true"></span>
								<span class="momcs-sync-amazon-btn-label"><?php esc_html_e( 'Sync from Amazon', 'multi-channel-for-woocommerce' ); ?></span>
							</button>
						<?php endif; ?>
					</div>
				</div>

				<!-- Filters popup: Sort, Category, Status only (search stays in toolbar) -->
				<div class="momcs-filters-modal-overlay" id="momcs-filters-modal-overlay" aria-hidden="true"></div>
				<div class="momcs-filters-modal" id="momcs-filters-modal" role="dialog" aria-modal="true" aria-labelledby="momcs-filters-modal-title" aria-hidden="true">
					<div class="momcs-filters-modal-header">
						<h2 class="momcs-filters-modal-title" id="momcs-filters-modal-title"><?php esc_html_e( 'Filters', 'multi-channel-for-woocommerce' ); ?></h2>
						<button type="button" class="momcs-filters-modal-close" id="momcs-filters-modal-close" aria-label="<?php esc_attr_e( 'Close', 'multi-channel-for-woocommerce' ); ?>">&times;</button>
					</div>
					<div class="momcs-filters-modal-body">
						<!-- Sort -->
						<div class="momcs-filters-modal-row">
							<label for="momcs-filter-sort" class="momcs-filters-modal-label"><?php esc_html_e( 'Sort by', 'multi-channel-for-woocommerce' ); ?></label>
							<select class="momcs-filter-select momcs-filter-select-in-modal" id="momcs-filter-sort">
								<option value="date-desc" <?php selected( $current_orderby, 'date-desc' ); ?>><?php esc_html_e( 'Newest first', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="date-asc" <?php selected( $current_orderby, 'date-asc' ); ?>><?php esc_html_e( 'Oldest first', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="name-asc" <?php selected( $current_orderby, 'name-asc' ); ?>><?php esc_html_e( 'Name A-Z', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="name-desc" <?php selected( $current_orderby, 'name-desc' ); ?>><?php esc_html_e( 'Name Z-A', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="price-asc" <?php selected( $current_orderby, 'price-asc' ); ?>><?php esc_html_e( 'Price: Low to High', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="price-desc" <?php selected( $current_orderby, 'price-desc' ); ?>><?php esc_html_e( 'Price: High to Low', 'multi-channel-for-woocommerce' ); ?></option>
							</select>
						</div>
						<!-- Category -->
						<div class="momcs-filters-modal-row">
							<label for="momcs-filter-category" class="momcs-filters-modal-label"><?php esc_html_e( 'Category', 'multi-channel-for-woocommerce' ); ?></label>
							<select class="momcs-filter-select momcs-filter-select-in-modal" id="momcs-filter-category">
								<option value=""><?php esc_html_e( 'All', 'multi-channel-for-woocommerce' ); ?></option>
								<?php if ( ! empty( $categories ) && ! is_wp_error( $categories ) ) : ?>
									<?php foreach ( $categories as $category ) : ?>
										<option value="<?php echo esc_attr( $category->term_id ); ?>" <?php selected( $current_category, (string) $category->term_id ); ?>><?php echo esc_html( $category->name ); ?></option>
									<?php endforeach; ?>
								<?php endif; ?>
							</select>
						</div>
						<!-- Status -->
						<div class="momcs-filters-modal-row">
							<label for="momcs-filter-status" class="momcs-filters-modal-label"><?php esc_html_e( 'Status', 'multi-channel-for-woocommerce' ); ?></label>
							<select class="momcs-filter-select momcs-filter-select-in-modal" id="momcs-filter-status">
								<option value=""><?php esc_html_e( 'All', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="uploaded" <?php selected( $current_status, 'uploaded' ); ?>><?php esc_html_e( 'Uploaded', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="discoverable" <?php selected( $current_status, 'discoverable' ); ?>><?php esc_html_e( 'Discoverable', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="processing" <?php selected( $current_status, 'processing' ); ?>><?php esc_html_e( 'Processing', 'multi-channel-for-woocommerce' ); ?></option>
								<option value="not_uploaded" <?php selected( $current_status, 'not_uploaded' ); ?>><?php esc_html_e( 'Not Uploaded', 'multi-channel-for-woocommerce' ); ?></option>
							</select>
						</div>
					</div>
					<div class="momcs-filters-modal-footer">
						<button type="button" class="momcs-filters-modal-clear" id="momcs-filters-clear"><?php esc_html_e( 'Clear', 'multi-channel-for-woocommerce' ); ?></button>
						<button type="button" class="momcs-filters-modal-apply" id="momcs-filters-apply"><?php esc_html_e( 'Apply', 'multi-channel-for-woocommerce' ); ?></button>
					</div>
				</div>

				<!-- Sync Status Row (for spinners and messages) -->

				<?php if ( empty( $products ) ) : ?>
					<!-- Empty State -->
					<div class="momcs-products-table-wrapper">
						<div class="momcs-products-empty">
							<svg class="momcs-products-empty-icon" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
								<path d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
							</svg>
							<h3><?php esc_html_e( 'No products found', 'multi-channel-for-woocommerce' ); ?></h3>
							<p><?php esc_html_e( 'Add some products to your WooCommerce store to get started.', 'multi-channel-for-woocommerce' ); ?></p>
						</div>
					</div>
				<?php else : ?>
					<!-- Top Pagination -->
					<?php $this->render_modern_pagination( $current_page, $total_pages, $total_products, $items_per_page, $start_item, $end_item, 'top' ); ?>

					<!-- Products Table -->
					<div class="momcs-products-table-wrapper">
						<table class="momcs-products-table">
							<thead>
								<tr>
									<th class="column-cb">
										<input type="checkbox" id="momcs-select-all" title="<?php esc_attr_e( 'Select All', 'multi-channel-for-woocommerce' ); ?>">
									</th>
									<th class="column-product"><?php esc_html_e( 'Product Details', 'multi-channel-for-woocommerce' ); ?></th>
									<th class="column-category"><?php esc_html_e( 'Category', 'multi-channel-for-woocommerce' ); ?></th>
									<th class="column-type"><?php esc_html_e( 'Type', 'multi-channel-for-woocommerce' ); ?></th>
									<th class="column-asin"><?php esc_html_e( 'ASIN', 'multi-channel-for-woocommerce' ); ?></th>
									<th class="column-price"><?php esc_html_e( 'Price', 'multi-channel-for-woocommerce' ); ?></th>
									<th class="column-stock"><?php esc_html_e( 'Stock', 'multi-channel-for-woocommerce' ); ?></th>
									<th class="column-status">
										<?php esc_html_e( 'Marketplace status', 'multi-channel-for-woocommerce' ); ?>
										<button type="button" class="momcs-amz-refresh-status-btn" id="momcs-amz-refresh-status" title="<?php esc_attr_e( 'Refresh status for all products', 'multi-channel-for-woocommerce' ); ?>">
											<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
												<path d="M21 3V8M21 8H16M21 8L18 5.29168C16.4077 3.86656 14.3051 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21C16.2832 21 19.8675 18.008 20.777 14"></path>
											</svg>
										</button>
									</th>
									<th class="column-issues"><?php esc_html_e( 'Issues', 'multi-channel-for-woocommerce' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $products as $product ) : ?>
									<?php $this->render_product_row( $product ); ?>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>

					<!-- Bottom Pagination -->
					<?php $this->render_modern_pagination( $current_page, $total_pages, $total_products, $items_per_page, $start_item, $end_item, 'bottom' ); ?>
				<?php endif; ?>
			</div>

			<!-- Logger UI -->
			<div class="momcs-sync-logger" id="momcs-sync-logger">
				<div class="momcs-sync-logger-header">
					<h2><?php esc_html_e( 'Sync Logs', 'multi-channel-for-woocommerce' ); ?></h2>
					<div class="momcs-sync-logger-actions">
						<button type="button" class="button" id="momcs-sync-toggle-logger">
							<?php esc_html_e( 'Hide Logs', 'multi-channel-for-woocommerce' ); ?>
						</button>
						<button type="button" class="button" id="momcs-sync-clear-logger">
							<?php esc_html_e( 'Clear Logs', 'multi-channel-for-woocommerce' ); ?>
						</button>
					</div>
				</div>
				<div class="momcs-sync-logger-content" id="momcs-sync-logger-content"></div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render a single product row in the modern table.
	 *
	 * @param array $product Product data array.
	 * @return void
	 */
	private function render_product_row( array $product ): void {
		$categories_array = ! empty( $product['categories'] ) ? explode( ', ', $product['categories'] ) : array();
		?>
		<tr data-product-id="<?php echo esc_attr( $product['id'] ); ?>">
			<td class="column-cb">
				<input type="checkbox" name="product_ids[]" value="<?php echo esc_attr( $product['id'] ); ?>">
			</td>
			<td class="column-product">
				<div class="momcs-product-details">
					<?php if ( $product['image'] ) : ?>
						<img src="<?php echo esc_url( $product['image'] ); ?>" alt="<?php echo esc_attr( $product['name'] ); ?>" class="momcs-product-thumb">
					<?php else : ?>
						<img src="<?php echo esc_url( wc_placeholder_img_src() ); ?>" alt="<?php esc_attr_e( 'Placeholder', 'multi-channel-for-woocommerce' ); ?>" class="momcs-product-thumb">
					<?php endif; ?>
					<div class="momcs-product-info">
						<a href="<?php echo esc_url( get_edit_post_link( $product['id'] ) ); ?>" class="momcs-product-name" target="_blank">
							<?php echo esc_html( $product['name'] ); ?>
						</a>
						<?php if ( ! empty( $product['sku'] ) ) : ?>
							<span class="momcs-product-sku-row">
								<strong class="momcs-sku-label"><?php esc_html_e( 'SKU', 'multi-channel-for-woocommerce' ); ?></strong>
								<span class="momcs-sku-value"><?php echo esc_html( $product['sku'] ); ?></span>
								<a href="<?php echo esc_url( get_edit_post_link( $product['id'] ) ); ?>" class="momcs-sku-edit-link" target="_blank"><?php esc_html_e( 'Edit', 'multi-channel-for-woocommerce' ); ?></a>
							</span>
						<?php endif; ?>
						<?php if ( empty( $product['has_amz_id'] ) ) : ?>
							<a href="<?php echo esc_url( get_edit_post_link( $product['id'] ) . '#momcs_sync_product_data' ); ?>" class="momcs-product-config-warning" title="<?php esc_attr_e( 'Product ID Value (UPC/EAN/ISBN/GTIN) is missing. Click to edit the product and set it under the Amazon tab.', 'multi-channel-for-woocommerce' ); ?>">
								<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
									<path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
								</svg>
							</a>
						<?php endif; ?>
					</div>
				</div>
			</td>
			<td class="column-category">
				<?php if ( ! empty( $categories_array ) ) : ?>
					<div class="momcs-category-pills">
						<?php foreach ( array_slice( $categories_array, 0, 2 ) as $cat ) : ?>
							<span class="momcs-category-pill"><?php echo esc_html( trim( $cat ) ); ?></span>
						<?php endforeach; ?>
						<?php if ( count( $categories_array ) > 2 ) : ?>
							<?php foreach ( array_slice( $categories_array, 2 ) as $cat ) : ?>
								<span class="momcs-category-pill momcs-category-pill-hidden"><?php echo esc_html( trim( $cat ) ); ?></span>
							<?php endforeach; ?>
							<span class="momcs-category-pill momcs-category-pill-toggle" role="button" tabindex="0" title="<?php esc_attr_e( 'Click to show all categories', 'multi-channel-for-woocommerce' ); ?>">+<?php echo esc_html( count( $categories_array ) - 2 ); ?></span>
						<?php endif; ?>
					</div>
				<?php else : ?>
					<span class="momcs-text-muted">&mdash;</span>
				<?php endif; ?>
			</td>
			<td class="column-type">
				<span class="momcs-type-badge momcs-type-badge-text <?php echo 'variable' === $product['type'] ? 'type-variable' : 'type-simple'; ?>">
					<?php echo 'variable' === $product['type'] ? esc_html__( 'Variable', 'multi-channel-for-woocommerce' ) : esc_html__( 'Simple', 'multi-channel-for-woocommerce' ); ?>
				</span>
			</td>
			<td class="column-asin">
				<?php if ( Utils::is_premium_plan() && ! empty( $product['marketplace_statuses'] ) ) : ?>
					<?php
					$asin_chips = array();
					foreach ( $product['marketplace_statuses'] as $mp_id => $mp_data ) {
						if ( empty( $mp_data['asin'] ) ) {
							continue;
						}
						$mp_info      = class_exists( Marketplace_Display_Helper::class ) ? Marketplace_Display_Helper::get_marketplace_info( $mp_id ) : null;
						$asin_chips[] = array(
							'asin'    => $mp_data['asin'],
							'mp_id'   => $mp_id,
							'mp_info' => $mp_info,
						);
					}
					?>
					<?php if ( ! empty( $asin_chips ) ) : ?>
						<div class="momcs-asin-chips">
							<?php foreach ( $asin_chips as $chip ) : ?>
								<?php
								$mp_name = ( null !== $chip['mp_info'] && ! empty( $chip['mp_info']['name'] ) ) ? $chip['mp_info']['name'] : '';
								$title   = ( '' !== $mp_name ? $mp_name . ' - ' : '' ) . esc_html__( 'ASIN', 'multi-channel-for-woocommerce' ) . ': ' . $chip['asin'];
								?>
								<span class="momcs-asin-chip momcs-icon-tooltip" title="<?php echo esc_attr( $title ); ?>">
									<?php if ( null !== $chip['mp_info'] && ! empty( $chip['mp_info']['flag'] ) ) : ?>
										<span class="momcs-mp-flag momcs-flag-<?php echo esc_attr( $chip['mp_info']['flag'] ); ?>"></span>
									<?php endif; ?>
									<code class="momcs-asin-value"><?php echo esc_html( $chip['asin'] ); ?></code>
								</span>
							<?php endforeach; ?>
						</div>
					<?php else : ?>
						<span class="momcs-asin-empty">&mdash;</span>
					<?php endif; ?>
				<?php elseif ( ! empty( $product['asin'] ) ) : ?>
					<span class="momcs-icon-tooltip" title="<?php esc_attr_e( 'ASIN', 'multi-channel-for-woocommerce' ); ?>: <?php echo esc_attr( $product['asin'] ); ?>">
						<code class="momcs-asin-value"><?php echo esc_html( $product['asin'] ); ?></code>
					</span>
				<?php else : ?>
					<span class="momcs-asin-empty">&mdash;</span>
				<?php endif; ?>
			</td>
			<td class="column-price">
				<div class="momcs-price-chips">
					<div class="momcs-price-chip woocommerce">
						<span class="momcs-price-chip-logo"></span>
						<span class="momcs-price-value"><?php echo wp_kses_post( $product['formatted_price'] ); ?></span>
					</div>
					<?php if ( Utils::is_premium_plan() && ! empty( $product['marketplace_statuses'] ) ) : ?>
						<?php foreach ( $product['marketplace_statuses'] as $mp_id => $mp_data ) : ?>
							<?php
							$has_single = ! empty( $mp_data['price'] );
							$has_range  = isset( $mp_data['price_min'] ) && isset( $mp_data['price_max'] );
							if ( ! $has_single && ! $has_range ) {
								continue;
							}
							$mp_info = null;
							if ( class_exists( Marketplace_Display_Helper::class ) ) {
								$mp_info = Marketplace_Display_Helper::get_marketplace_info( $mp_id );
							}
							if ( null === $mp_info ) {
								continue;
							}
							if ( $has_range ) {
								$min = (float) $mp_data['price_min'];
								$max = (float) $mp_data['price_max'];
								$price_html = $min === $max
									? wc_price( $min )
									: wc_price( $min ) . ' &ndash; ' . wc_price( $max );
							} else {
								$price_html = wc_price( $mp_data['price'] );
							}
							?>
							<div class="momcs-price-chip amazon" title="Amazon <?php echo esc_attr( $mp_info['name'] ); ?>">
								<span class="momcs-price-chip-logo"></span>
								<span class="momcs-mp-flag momcs-flag-<?php echo esc_attr( $mp_info['flag'] ); ?>"></span>
								<span class="momcs-price-value"><?php echo wp_kses_post( $price_html ); ?></span>
							</div>
						<?php endforeach; ?>
					<?php endif; ?>
				</div>
			</td>
			<td class="column-stock">
				<?php if ( 'instock' === $product['stock_status'] ) : ?>
					<span class="momcs-stock-badge in-stock momcs-icon-tooltip" title="<?php esc_attr_e( 'In Stock', 'multi-channel-for-woocommerce' ); ?>">
						<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m8 11 2 2 4-4"/><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
					</span>
				<?php else : ?>
					<span class="momcs-stock-badge out-of-stock momcs-icon-tooltip" title="<?php esc_attr_e( 'Out of Stock', 'multi-channel-for-woocommerce' ); ?>">
						<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m13.5 8.5-5 5"/><path d="m8.5 8.5 5 5"/><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
					</span>
				<?php endif; ?>
			</td>
			<td class="column-status">
				<?php $this->render_modern_status_chips( $product ); ?>
			</td>
			<td class="column-issues">
				<?php if ( $product['has_issues'] ) : ?>
					<button type="button" class="momcs-issues-btn momcs-amz-issues-btn momcs-icon-tooltip" data-product-id="<?php echo esc_attr( $product['id'] ); ?>" title="<?php esc_attr_e( 'View Issues', 'multi-channel-for-woocommerce' ); ?>">
						<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-icon-issues"><path d="M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>
					</button>
				<?php endif; ?>
			</td>
		</tr>
		<?php
	}

	/**
	 * Render modern status chips for a product.
	 *
	 * @param array $product Product data array.
	 * @return void
	 */
	private function render_modern_status_chips( array $product ): void {
		$marketplace_statuses = $product['marketplace_statuses'] ?? array();

		if ( Utils::is_premium_plan() && ! empty( $marketplace_statuses ) ) {
			echo '<div class="momcs-marketplace-chips">';
			foreach ( $marketplace_statuses as $marketplace_id => $data ) {
				if ( empty( $data['status'] ) ) {
					continue;
				}
				$mp_info = null;
				if ( class_exists( Marketplace_Display_Helper::class ) ) {
					$mp_info = Marketplace_Display_Helper::get_marketplace_info( $marketplace_id );
				}
				if ( null === $mp_info ) {
					continue;
				}
				$status_class   = $this->get_status_css_class( $data['status'] );
				$status_label   = $this->get_status_label( $data['status'] );
				$status_tooltip = $this->get_status_tooltip( $data['status'] );
				?>
				<div class="momcs-marketplace-chip <?php echo esc_attr( $status_class ); ?> momcs-icon-tooltip" title="<?php echo esc_attr( $mp_info['name'] . ' - ' . $status_label . ': ' . $status_tooltip ); ?>">
					<?php $this->render_status_icon( $data['status'] ); ?>
					<span class="momcs-mp-flag momcs-flag-<?php echo esc_attr( $mp_info['flag'] ); ?>"></span>
				</div>
				<?php
			}
			echo '</div>';
			return;
		}

		// Legacy single status.
		$status         = $product['listing_status'] ?? '';
		$status_class   = $this->get_status_css_class( $status );
		$status_label   = $this->get_status_label( $status );
		$status_tooltip = $this->get_status_tooltip( $status );
		?>
		<div class="momcs-marketplace-chips">
			<div class="momcs-marketplace-chip <?php echo esc_attr( $status_class ); ?> momcs-icon-tooltip" title="<?php echo esc_attr( $status_label . ': ' . $status_tooltip ); ?>">
				<?php $this->render_status_icon( $status ); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render status icon based on status.
	 *
	 * @param string $status The status string.
	 * @return void
	 */
	private function render_status_icon( string $status ): void {
		$status_lower = strtolower( $status );
		switch ( $status_lower ) {
			case 'uploaded':
			case 'buyable':
			case 'success':
				// Circle check icon for uploaded.
				echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-uploaded"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>';
				break;
			case 'discoverable':
				// Binoculars icon for discoverable.
				echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-discoverable"><path d="M10 10h4"/><path d="M19 7V4a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3"/><path d="M20 21a2 2 0 0 0 2-2v-3.851c0-1.39-2-2.962-2-4.829V8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v11a2 2 0 0 0 2 2z"/><path d="M 22 16 L 2 16"/><path d="M4 21a2 2 0 0 1-2-2v-3.851c0-1.39 2-2.962 2-4.829V8a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v11a2 2 0 0 1-2 2z"/><path d="M9 7V4a1 1 0 0 0-1-1H6a1 1 0 0 0-1 1v3"/></svg>';
				break;
			case 'processing':
			case 'pending':
				// Loader icon for processing.
				echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-processing momcs-icon-spin"><path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/></svg>';
				break;
			case 'failed':
			case 'error':
				// X circle icon for failed.
				echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-error"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>';
				break;
			default:
				// Default - not uploaded icon.
				echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-status-icon-default"><circle cx="12" cy="12" r="10"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>';
				break;
		}
	}

	/**
	 * Render modern pagination component.
	 *
	 * @param int    $current_page   Current page number.
	 * @param int    $total_pages    Total number of pages.
	 * @param int    $total_products Total number of products.
	 * @param int    $items_per_page Items per page.
	 * @param int    $start_item     Start item number.
	 * @param int    $end_item       End item number.
	 * @param string $position       Position: 'top' or 'bottom'.
	 * @return void
	 */
	private function render_modern_pagination( int $current_page, int $total_pages, int $total_products, int $items_per_page, int $start_item, int $end_item, string $position = 'bottom' ): void {
		if ( $total_pages <= 1 && 'top' === $position ) {
			return;
		}
		?>
		<div class="momcs-pagination-wrapper <?php echo esc_attr( $position ); ?>">
			<div class="momcs-pagination-per-page">
				<span><?php esc_html_e( 'Show', 'multi-channel-for-woocommerce' ); ?></span>
				<select class="momcs-per-page-select" id="momcs-per-page-<?php echo esc_attr( $position ); ?>">
					<?php foreach ( array( 10, 25, 50, 100 ) as $option ) : ?>
						<option value="<?php echo esc_attr( $option ); ?>" <?php selected( $items_per_page, $option ); ?>>
							<?php echo esc_html( $option ); ?>
						</option>
					<?php endforeach; ?>
				</select>
				<span><?php esc_html_e( 'entries', 'multi-channel-for-woocommerce' ); ?></span>
			</div>

			<div class="momcs-pagination-info">
				<?php
				printf(
					/* translators: 1: Start item, 2: End item, 3: Total products */
					esc_html__( 'Showing %1$s-%2$s of %3$s products', 'multi-channel-for-woocommerce' ),
					'<strong>' . esc_html( number_format_i18n( $start_item ) ) . '</strong>',
					'<strong>' . esc_html( number_format_i18n( $end_item ) ) . '</strong>',
					'<strong>' . esc_html( number_format_i18n( $total_products ) ) . '</strong>'
				);
				?>
			</div>

			<?php if ( $total_pages > 1 ) : ?>
			<div class="momcs-pagination-nav">
				<!-- First Page -->
				<a href="<?php echo esc_url( add_query_arg( 'paged', 1 ) ); ?>" class="momcs-page-btn momcs-page-first" <?php echo $current_page <= 1 ? 'disabled' : ''; ?>>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
						<polyline points="11 17 6 12 11 7"></polyline>
						<polyline points="18 17 13 12 18 7"></polyline>
					</svg>
				</a>

				<!-- Previous Page -->
				<a href="<?php echo esc_url( add_query_arg( 'paged', max( 1, $current_page - 1 ) ) ); ?>" class="momcs-page-btn momcs-page-prev" <?php echo $current_page <= 1 ? 'disabled' : ''; ?>>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
						<polyline points="15 18 9 12 15 6"></polyline>
					</svg>
				</a>

				<!-- Page Numbers -->
				<div class="momcs-page-numbers">
					<?php
					$range = 2;
					$start = max( 1, $current_page - $range );
					$end   = min( $total_pages, $current_page + $range );

					if ( $start > 1 ) {
						echo '<a href="' . esc_url( add_query_arg( 'paged', 1 ) ) . '" class="momcs-page-num">1</a>';
						if ( $start > 2 ) {
							echo '<span class="momcs-page-ellipsis">...</span>';
						}
					}

					for ( $i = $start; $i <= $end; $i++ ) {
						$active_class = ( $i === $current_page ) ? 'active' : '';
						echo '<a href="' . esc_url( add_query_arg( 'paged', $i ) ) . '" class="momcs-page-num ' . esc_attr( $active_class ) . '">' . esc_html( $i ) . '</a>';
					}

					if ( $end < $total_pages ) {
						if ( $end < $total_pages - 1 ) {
							echo '<span class="momcs-page-ellipsis">...</span>';
						}
						echo '<a href="' . esc_url( add_query_arg( 'paged', $total_pages ) ) . '" class="momcs-page-num">' . esc_html( $total_pages ) . '</a>';
					}
					?>
				</div>

				<!-- Next Page -->
				<a href="<?php echo esc_url( add_query_arg( 'paged', min( $total_pages, $current_page + 1 ) ) ); ?>" class="momcs-page-btn momcs-page-next" <?php echo $current_page >= $total_pages ? 'disabled' : ''; ?>>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
						<polyline points="9 18 15 12 9 6"></polyline>
					</svg>
				</a>

				<!-- Last Page -->
				<a href="<?php echo esc_url( add_query_arg( 'paged', $total_pages ) ); ?>" class="momcs-page-btn momcs-page-last" <?php echo $current_page >= $total_pages ? 'disabled' : ''; ?>>
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
						<polyline points="13 17 18 12 13 7"></polyline>
						<polyline points="6 17 11 12 6 7"></polyline>
					</svg>
				</a>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Render status chips for a product.
	 *
	 * For premium users, shows per-marketplace status chips with Amazon logo, flag, and status dot.
	 * Falls back to legacy single-status display for standard users or when no marketplace data exists.
	 *
	 * @param array $product Product data array with listing_status and marketplace_statuses.
	 * @return void
	 */
	private function render_status_chips( array $product ): void {
		$marketplace_statuses = $product['marketplace_statuses'] ?? array();

		// Premium: Show per-marketplace status chips if data exists.
		if ( Utils::is_premium_plan() && ! empty( $marketplace_statuses ) ) {
			echo '<div class="momcs-marketplace-status-chips">';

			foreach ( $marketplace_statuses as $marketplace_id => $data ) {
				// Skip marketplaces without status data.
				if ( empty( $data['status'] ) ) {
					continue;
				}

				// Get marketplace display info.
				$mp_info = null;
				if ( class_exists( Marketplace_Display_Helper::class ) ) {
					$mp_info = Marketplace_Display_Helper::get_marketplace_info( $marketplace_id );
				}

				// Skip if we can't get marketplace info.
				if ( null === $mp_info ) {
					continue;
				}

				$status       = $data['status'];
				$status_class = $this->get_status_css_class( $status );
				$status_label = $this->get_status_label( $status );
				?>
				<div class="momcs-marketplace-status-chip-wrapper">
					<div class="momcs-marketplace-status-chip <?php echo esc_attr( $status_class ); ?>">
					<span class="momcs-mp-status-dot <?php echo esc_attr( $status_class ); ?>"></span>	
					<span class="momcs-mp-logo amazon-logo"></span>
					<span class="momcs-mp-flag momcs-flag-<?php echo esc_attr( $mp_info['flag'] ); ?>"></span>
					</div>
					<span class="momcs-mp-tooltip"><?php echo esc_html( $mp_info['name'] . ' - ' . $status_label ); ?></span>
				</div>
				<?php
			}

			echo '</div>';
			return;
		}

		// Fallback: Legacy single-status display.
		$this->render_legacy_status_chip( $product['listing_status'] ?? '' );
	}

	/**
	 * Render legacy single-status chip for non-premium users or when no marketplace data exists.
	 *
	 * @param string $listing_status The product's listing status.
	 * @return void
	 */
	private function render_legacy_status_chip( string $listing_status ): void {
		switch ( $listing_status ) {
			case 'uploaded':
			case 'BUYABLE':
				echo '<div class="momcs-sync-status-chip success"><span class="momcs-sync-status-dot"></span>' . esc_html__( 'Uploaded', 'multi-channel-for-woocommerce' ) . '</div>';
				break;
			case 'discoverable':
			case 'DISCOVERABLE':
				echo '<div class="momcs-sync-status-chip discoverable"><span class="momcs-sync-status-dot"></span>' . esc_html__( 'Discoverable', 'multi-channel-for-woocommerce' ) . '</div>';
				break;
			case 'processing':
				echo '<div class="momcs-sync-status-chip processing">';
				echo '<svg width="12" height="12" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right: 4px; flex-shrink: 0;"><path d="M7.706 0.290 C 7.484 0.362,7.356 0.490,7.294 0.699 C 7.259 0.816,7.253 1.088,7.253 2.508 C 7.253 4.389,7.251 4.365,7.443 4.557 C 7.700 4.813,8.300 4.813,8.557 4.557 C 8.749 4.365,8.747 4.389,8.747 2.508 C 8.747 0.688,8.744 0.656,8.596 0.480 C 8.472 0.333,8.339 0.284,8.040 0.276 C 7.893 0.272,7.743 0.278,7.706 0.290 M2.753 2.266 C 2.595 2.338,2.362 2.566,2.281 2.728 C 2.197 2.897,2.193 3.085,2.269 3.253 C 2.343 3.418,4.667 5.750,4.850 5.843 C 5.109 5.976,5.375 5.911,5.643 5.649 C 5.907 5.391,5.977 5.111,5.843 4.850 C 5.750 4.667,3.418 2.343,3.253 2.269 C 3.101 2.200,2.901 2.199,2.753 2.266 M12.853 2.282 C 12.730 2.339,12.520 2.536,11.518 3.541 C 10.597 4.464,10.316 4.762,10.271 4.860 C 10.195 5.025,10.196 5.216,10.272 5.378 C 10.342 5.528,10.572 5.764,10.727 5.845 C 10.884 5.927,11.117 5.926,11.280 5.843 C 11.447 5.757,13.757 3.447,13.843 3.280 C 13.926 3.118,13.927 2.884,13.846 2.729 C 13.764 2.572,13.552 2.364,13.392 2.283 C 13.213 2.192,13.048 2.192,12.853 2.282 M0.699 7.292 C 0.404 7.385,0.258 7.620,0.258 7.999 C 0.259 8.386,0.403 8.618,0.698 8.706 C 0.816 8.741,1.079 8.747,2.508 8.747 C 3.997 8.747,4.196 8.742,4.318 8.702 C 4.498 8.644,4.644 8.498,4.702 8.318 C 4.788 8.053,4.745 7.677,4.608 7.491 C 4.578 7.451,4.492 7.384,4.417 7.343 L 4.280 7.267 2.547 7.261 C 1.152 7.257,0.791 7.263,0.699 7.292 M11.745 7.278 C 11.622 7.308,11.452 7.411,11.392 7.492 C 11.255 7.677,11.212 8.053,11.298 8.318 C 11.356 8.498,11.502 8.644,11.682 8.702 C 11.804 8.742,12.003 8.747,13.492 8.747 C 14.921 8.747,15.184 8.741,15.302 8.706 C 15.597 8.618,15.741 8.386,15.742 7.999 C 15.742 7.614,15.595 7.383,15.290 7.291 C 15.187 7.260,14.864 7.254,13.496 7.256 C 12.578 7.258,11.790 7.268,11.745 7.278 M4.853 10.282 C 4.730 10.339,4.520 10.536,3.518 11.541 C 2.597 12.464,2.316 12.762,2.271 12.860 C 2.195 13.025,2.196 13.216,2.272 13.378 C 2.342 13.528,2.572 13.764,2.727 13.845 C 2.884 13.927,3.117 13.926,3.280 13.843 C 3.447 13.757,5.757 11.447,5.843 11.280 C 5.926 11.118,5.927 10.884,5.846 10.729 C 5.764 10.572,5.552 10.364,5.392 10.283 C 5.213 10.192,5.048 10.192,4.853 10.282 M10.753 10.266 C 10.595 10.338,10.362 10.566,10.281 10.728 C 10.197 10.897,10.193 11.085,10.269 11.253 C 10.343 11.418,12.667 13.750,12.850 13.843 C 13.109 13.976,13.375 13.911,13.643 13.649 C 13.907 13.391,13.977 13.111,13.843 12.850 C 13.750 12.667,11.418 10.343,11.253 10.269 C 11.101 10.200,10.901 10.199,10.753 10.266 M7.745 11.277 C 7.620 11.309,7.451 11.412,7.392 11.492 C 7.254 11.678,7.253 11.691,7.253 13.489 C 7.253 14.921,7.259 15.184,7.294 15.302 C 7.382 15.597,7.615 15.741,8.000 15.741 C 8.385 15.741,8.618 15.597,8.706 15.302 C 8.768 15.090,8.767 11.875,8.704 11.690 C 8.644 11.514,8.575 11.430,8.420 11.346 C 8.310 11.286,8.246 11.271,8.057 11.264 C 7.930 11.259,7.790 11.265,7.745 11.277 " stroke="none" fill-rule="evenodd" fill="#996800"/></svg>';
				echo esc_html__( 'Processing', 'multi-channel-for-woocommerce' );
				echo '</div>';
				break;
			case 'pending':
				echo '<div class="momcs-sync-status-chip pending"><span class="momcs-sync-status-dot"></span>' . esc_html__( 'Pending', 'multi-channel-for-woocommerce' ) . '</div>';
				break;
			case 'failed':
				echo '<div class="momcs-sync-status-chip error"><span class="momcs-sync-status-dot"></span>' . esc_html__( 'Failed', 'multi-channel-for-woocommerce' ) . '</div>';
				break;
			default:
				echo '<div class="momcs-sync-status-chip danger"><span class="momcs-sync-status-dot"></span>' . esc_html__( 'Not uploaded', 'multi-channel-for-woocommerce' ) . '</div>';
		}
	}

	/**
	 * Get CSS class for a status value.
	 *
	 * @param string $status The status value.
	 * @return string CSS class name.
	 */
	private function get_status_css_class( string $status ): string {
		$status_map = array(
			'uploaded'     => 'success',
			'BUYABLE'      => 'success',
			'discoverable' => 'discoverable',
			'DISCOVERABLE' => 'discoverable',
			'processing'   => 'processing',
			'pending'      => 'pending',
			'failed'       => 'error',
		);

		return $status_map[ $status ] ?? 'danger';
	}

	/**
	 * Get human-readable label for a status value.
	 *
	 * @param string $status The status value.
	 * @return string Human-readable status label.
	 */
	private function get_status_label( string $status ): string {
		$label_map = array(
			'uploaded'     => __( 'Uploaded', 'multi-channel-for-woocommerce' ),
			'BUYABLE'      => __( 'Buyable', 'multi-channel-for-woocommerce' ),
			'discoverable' => __( 'Discoverable', 'multi-channel-for-woocommerce' ),
			'DISCOVERABLE' => __( 'Discoverable', 'multi-channel-for-woocommerce' ),
			'processing'   => __( 'Processing', 'multi-channel-for-woocommerce' ),
			'pending'      => __( 'Pending', 'multi-channel-for-woocommerce' ),
			'failed'       => __( 'Failed', 'multi-channel-for-woocommerce' ),
		);

		return $label_map[ $status ] ?? __( 'Not uploaded', 'multi-channel-for-woocommerce' );
	}

	/**
	 * Get descriptive tooltip text for a status value.
	 *
	 * @param string $status The status value.
	 * @return string Descriptive tooltip text.
	 */
	private function get_status_tooltip( string $status ): string {
		$tooltip_map = array(
			'uploaded'     => __( "Your product details have been sent to Amazon, but they're still being processed. Wait a bit or check for errors to move forward.", 'multi-channel-for-woocommerce' ),
			'BUYABLE'      => __( 'Great news! Customers can find your product AND buy it right now. It has price, stock, and follows all Amazon rules.', 'multi-channel-for-woocommerce' ),
			'discoverable' => __( "Customers can see and search for your product on Amazon. But they can't buy it yet — fix issues like price or stock to make it buyable.", 'multi-channel-for-woocommerce' ),
			'DISCOVERABLE' => __( "Customers can see and search for your product on Amazon. But they can't buy it yet — fix issues like price or stock to make it buyable.", 'multi-channel-for-woocommerce' ),
			'processing'   => __( 'Your product is currently being processed by Amazon. This may take a few minutes.', 'multi-channel-for-woocommerce' ),
			'pending'      => __( 'Your product listing is pending. Amazon is reviewing the submission.', 'multi-channel-for-woocommerce' ),
			'failed'       => __( 'The listing failed. Check the Issues column for details on what went wrong.', 'multi-channel-for-woocommerce' ),
		);

		return $tooltip_map[ $status ] ?? __( 'This product has not been uploaded to Amazon yet.', 'multi-channel-for-woocommerce' );
	}
}
