/**
 * AIEO Stock Recovery — deep-link focus for a specific product variation.
 *
 * A `product_variation` post can't be opened directly in the editor, so the
 * Stock Recovery tables link a variation to its PARENT product and append
 * `aieo_focus_variation=<id>`. On the product-edit screen this script:
 *   1) opens the product's "Variations" tab,
 *   2) waits for the variations to AJAX-load,
 *   3) if the target isn't on the current page, walks the variation pagination
 *      page-by-page until it finds it (handles paginated variation sets),
 *   4) scrolls to + expands + briefly highlights the target variation row.
 */
(function ($) {
	'use strict';
	$(function () {
		var vid = parseInt(new URLSearchParams(window.location.search).get('aieo_focus_variation'), 10);
		if (!vid) { return; }

		// Ask WooCommerce to load all variations on one page (up to 200) so the
		// target is present without paging. WC reads the page size from one of
		// these localized objects at load time; setting it BEFORE we open the tab
		// makes the first AJAX load return everything. Only affects this view; the
		// page-walk below is the fallback if it doesn't take, or there are >200.
		['woocommerce_admin_meta_boxes_variations', 'woocommerce_admin_meta_boxes'].forEach(function (k) {
			try {
				if (window[k] && parseInt(window[k].variations_per_page, 10) < 200) {
					window[k].variations_per_page = 200;
				}
			} catch (e) { /* noop */ }
		});

		// Open the Variations tab (covers WC class variants + the panel anchor).
		var $tab = $('.product_data_tabs li.variations_options > a, .product_data_tabs li.variations_tab > a').first();
		if (!$tab.length) { $tab = $('a[href="#variable_product_options"]').first(); }
		if (!$tab.length) { return; }
		$tab.trigger('click');

		function $panel() { return $('#variable_product_options'); }

		function findRow() {
			return $panel().find('.woocommerce_variation').filter(function () {
				var $r = $(this), hit = false;
				$r.find('input[name^="variable_post_id"]').each(function () {
					if (parseInt(this.value, 10) === vid) { hit = true; return false; }
				});
				if (hit) { return true; }
				return parseInt($r.find('.variation_id, .variation-id').first().text(), 10) === vid;
			}).first();
		}

		function curPage() {
			var $c = $panel().find('.current-page').first();
			var v = $c.is('input') ? $c.val() : $c.text();
			return parseInt(v, 10) || 1;
		}
		function totalPages() { return parseInt($panel().find('.total-pages').first().text(), 10) || 1; }

		function highlight($row) {
			if ($row.hasClass('closed')) { $row.children('h3').trigger('click'); } // WC's own expand
			$('html, body').animate({ scrollTop: Math.max(0, $row.offset().top - 90) }, 400);
			var prev = $row.css('box-shadow');
			$row.css({
				'transition': 'box-shadow .35s ease, background-color .35s ease',
				'box-shadow': '0 0 0 3px #f59e0b',
				'background-color': '#fffbeb'
			});
			setTimeout(function () { $row.css({ 'box-shadow': prev || 'none', 'background-color': '' }); }, 2800);
		}

		// 1) Wait for the first page of variations to render, then walk pages.
		var t1 = 0;
		var wait1 = setInterval(function () {
			t1++;
			if ($panel().find('.woocommerce_variation').length || t1 > 120) {
				clearInterval(wait1);
				walk();
			}
		}, 100);

		// 2) Search the current page; if absent, advance pagination and retry.
		function walk() {
			var $row = findRow();
			if ($row.length) { highlight($row); return; }
			var cur = curPage();
			if (cur >= totalPages()) { return; } // exhausted — not found (deleted?)
			var $next = $panel().find('.next-page').first();
			if (!$next.length || $next.hasClass('disabled') || $next.is('[disabled]')) { return; }
			$next.trigger('click');
			var t2 = 0;
			var wait2 = setInterval(function () {
				t2++;
				// page index advanced (AJAX done) or ~8s timeout → re-search.
				if (curPage() > cur || t2 > 80) {
					clearInterval(wait2);
					setTimeout(walk, 350);
				}
			}, 100);
		}
	});
})(jQuery);
