/**
 * Automotive Inventory Importer — admin scripts
 *
 * Behaviors: Quick Start Guide collapse/hide, notice dismissal, field-mapping
 * custom-target toggle, server file browser, live feed-link test, page-template
 * token preview, and the "Sync now" busy state. Configuration and translated
 * strings arrive via wp_localize_script as the global `afiAdmin`.
 */
/* global jQuery, afiAdmin, tb_show, tb_remove, ajaxurl */
(function ($) {
	'use strict';

	var cfg = window.afiAdmin || {};

	/* --- Quick Start Guide show/hide/collapse (localStorage) --------------- */
	function initQuickStart() {
		var HIDDEN = 'afi_qsg_hidden';
		var COLLAPSED = 'afi_qsg_collapsed';
		var sidebar = document.getElementById('afi-qsg-sidebar');
		var showWrap = document.getElementById('afi-qsg-show-wrap');
		if (!sidebar || !showWrap) {
			return;
		}
		var body = sidebar.querySelector('.afi-qsg-body');
		var toggle = sidebar.querySelector('.afi-qsg-toggle');
		var hideBtn = sidebar.querySelector('.afi-qsg-hide');
		var showBtn = document.getElementById('afi-qsg-show');

		function get(k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } }
		function set(k, v) { try { window.localStorage.setItem(k, v); } catch (e) {} }
		function del(k) { try { window.localStorage.removeItem(k); } catch (e) {} }

		function applyHidden(hidden) {
			sidebar.style.display = hidden ? 'none' : '';
			showWrap.style.display = hidden ? 'block' : 'none';
		}
		function applyCollapsed(collapsed) {
			if (!body || !toggle) { return; }
			body.style.display = collapsed ? 'none' : '';
			toggle.innerHTML = collapsed ? '&#9656;' : '&#9662;';
			toggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
			var i18n = cfg.i18n || {};
			toggle.setAttribute('title', collapsed ? (i18n.expand || 'Expand') : (i18n.collapse || 'Collapse'));
		}

		applyHidden(get(HIDDEN) === '1');
		applyCollapsed(get(COLLAPSED) === '1');

		if (toggle) {
			toggle.addEventListener('click', function () {
				var collapsed = get(COLLAPSED) !== '1';
				set(COLLAPSED, collapsed ? '1' : '0');
				applyCollapsed(collapsed);
			});
		}
		if (hideBtn) {
			hideBtn.addEventListener('click', function () {
				set(HIDDEN, '1');
				applyHidden(true);
			});
		}
		if (showBtn) {
			showBtn.addEventListener('click', function () {
				del(HIDDEN);
				applyHidden(false);
			});
		}
	}

	/* --- Dismissible banners (review / survey / activation) --------------- */
	function initBannerDismiss() {
		$('.notice[data-dismiss-type]').on('click', '.notice-dismiss', function () {
			var type = $(this).closest('.notice').data('dismiss-type');
			$.post(ajaxurl, {
				action: 'afi_dismiss_banner',
				type: type,
				nonce: cfg.dismissNonce
			});
		});
	}

	/* --- Field mapping: reveal custom-target input ------------------------ */
	function initMappingCustomToggle() {
		function toggle($select) {
			var $input = $select.closest('td').find('.afi-custom-target');
			if ($select.val() === '__afi_custom__') {
				$input.show().attr('required', true).trigger('focus');
			} else {
				$input.hide().removeAttr('required');
			}
		}
		$('.afi-target-select').each(function () {
			toggle($(this));
		}).on('change', function () {
			toggle($(this));
		});
	}

	/* --- Server file browser (thickbox) ----------------------------------- */
	function initFileBrowser() {
		$('#afi_browse_file').on('click', function (e) {
			e.preventDefault();
			var currentPath = $('#afi_xml_file_path').val() || cfg.abspath || '';
			// Remove any modal left over from a previous click so we never
			// accumulate duplicate-ID nodes (which confuse selectors/thickbox).
			$('#afi-file-browser-modal').remove();
			var modal = $('<div id="afi-file-browser-modal" style="display:none;"><div id="afi-file-browser-content"></div></div>');
			$('body').append(modal);
			$.post(ajaxurl, {
				action: 'afi_browse_files',
				path: currentPath,
				nonce: cfg.browseNonce
			}, function (response) {
				if (response.success) {
					$('#afi-file-browser-content').html(response.data.html);
					if (typeof tb_show === 'function') {
						tb_show(cfg.i18n.browseTitle || 'Browse Server Files', '#TB_inline?inlineId=afi-file-browser-modal&width=600&height=400');
					}
				}
			});
		});

		$(document).on('click', '.afi-file-item', function (e) {
			e.preventDefault();
			$('#afi_xml_file_path').val($(this).data('path'));
			if (typeof tb_remove === 'function') { tb_remove(); }
		});

		$(document).on('click', '.afi-folder-item', function (e) {
			e.preventDefault();
			$.post(ajaxurl, {
				action: 'afi_browse_files',
				path: $(this).data('path'),
				nonce: cfg.browseNonce
			}, function (response) {
				if (response.success) {
					$('#afi-file-browser-content').html(response.data.html);
				}
			});
		});
	}

	/* --- Live "Check feed link" test -------------------------------------- */
	function initFeedTest() {
		var $btn = $('#afi_test_feed');
		if (!$btn.length) {
			return;
		}
		var $result = $('#afi-feed-test-result');
		$btn.on('click', function (e) {
			e.preventDefault();
			var url = $.trim($('#afi_xml_file_path').val());
			if (!url) {
				$result.attr('class', 'afi-feed-test-result is-bad')
					.text(cfg.i18n.feedTestEmpty || 'Enter a feed link or pick a file first.');
				return;
			}
			$result.attr('class', 'afi-feed-test-result is-busy')
				.text(cfg.i18n.feedTestBusy || 'Checking your feed link…');
			$.post(ajaxurl, {
				action: 'afi_test_feed',
				url: url,
				nonce: cfg.testNonce
			}).done(function (response) {
				if (response && response.success) {
					$result.attr('class', 'afi-feed-test-result is-ok')
						.text('✓ ' + response.data.message);
				} else {
					var msg = (response && response.data && response.data.message) ? response.data.message : (cfg.i18n.feedTestFail || 'We could not check that link. Please try again.');
					$result.attr('class', 'afi-feed-test-result is-bad').text('✗ ' + msg);
				}
			}).fail(function () {
				$result.attr('class', 'afi-feed-test-result is-bad')
					.text('✗ ' + (cfg.i18n.feedTestFail || 'We could not check that link. Please try again.'));
			});
		});
	}

	/* --- "Sync now" blocking overlay -------------------------------------- */
	function showSyncOverlay() {
		if (document.getElementById('afi-sync-overlay')) {
			return;
		}
		var i18n = cfg.i18n || {};
		var $box = $('<div class="afi-sync-overlay__box" />')
			.append($('<div class="afi-spinner" aria-hidden="true" />'))
			.append($('<h2 />').text(i18n.syncOverlayTitle || 'Syncing your inventory…'))
			.append($('<p />').text(i18n.syncOverlayBody || 'Please keep this window open and don’t navigate away. This can take a minute for large feeds.'));
		var $overlay = $('<div id="afi-sync-overlay" class="afi-sync-overlay" />')
			.attr({ role: 'alertdialog', 'aria-live': 'assertive', 'aria-busy': 'true' })
			.append($box);
		$('body').append($overlay);
	}

	function initSyncBusy() {
		$('.afi-sync-trigger').on('click', function () {
			var $btn = $(this);
			var href = $btn.data('href');
			if (!href) {
				return;
			}
			if (!window.confirm(cfg.i18n.syncConfirm || 'Run a fresh import now?')) {
				return;
			}
			$('.afi-sync-trigger').prop('disabled', true);
			showSyncOverlay();
			window.location.href = href;
		});
	}

	/* --- Page-template token preview -------------------------------------- */
	function initTokenPreview() {
		var sample = cfg.sample || {};

		function render(value) {
			if (!value) {
				return '<em>' + (cfg.i18n.previewEmpty || 'Nothing yet — type a template above.') + '</em>';
			}
			// Escape the whole template first so any HTML the user typed renders
			// as literal text, then substitute tokens on the escaped string.
			return escapeHtml(value).replace(/\{([^}]+)\}/g, function (full, token) {
				var key = $.trim(token);
				if (Object.prototype.hasOwnProperty.call(sample, key) && sample[key] !== '') {
					return '<strong>' + escapeHtml(sample[key]) + '</strong>';
				}
				// No data for this token in the sample vehicle — show it struck
				// through so users see it will simply be left out (matching import).
				// `key` is already escaped (it came from the escaped template above).
				return '<span style="color:#999;text-decoration:line-through;">{' + key + '}</span>';
			});
		}

		function escapeHtml(str) {
			return String(str)
				.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
				.replace(/"/g, '&quot;').replace(/'/g, '&#039;');
		}

		$('.afi-token-input').each(function () {
			var $field = $(this);
			var $preview = $('#' + $field.data('preview'));
			if (!$preview.length) {
				return;
			}
			function update() { $preview.html(render($field.val())); }
			$field.on('input keyup change', update);
			update();
		});
	}

	$(function () {
		initQuickStart();
		initBannerDismiss();
		initMappingCustomToggle();
		initFileBrowser();
		initFeedTest();
		initSyncBusy();
		initTokenPreview();
	});
})(jQuery);
