/**
 * Vehicle Data meta box — Gallery, Video, taxonomy multi-selects, Make→Model cascade.
 *
 * Expects `trxAdVehicleData` global from wp_localize_script with i18n strings.
 *
 * @package ThemeREX\AutoDealer
 */
(function () {
	'use strict';

	var i18n = (typeof trxAdVehicleData !== 'undefined') ? trxAdVehicleData.i18n : {};

	/* --- Tab switching --- */
	var tabs = document.querySelectorAll('.trx-ad-vdata-tab');
	var panels = document.querySelectorAll('.trx-ad-vdata-panel');

	tabs.forEach(function (tab) {
		tab.addEventListener('click', function (e) {
			e.preventDefault();
			var target = this.getAttribute('data-tab');
			tabs.forEach(function (t) { t.classList.remove('trx-ad-vdata-tab--active'); });
			panels.forEach(function (p) { p.classList.remove('trx-ad-vdata-panel--active'); });
			this.classList.add('trx-ad-vdata-tab--active');
			var panel = document.querySelector('[data-panel="' + target + '"]');
			if (panel) panel.classList.add('trx-ad-vdata-panel--active');
		});
	});

	/* ================================================================
	   Gallery
	   ================================================================ */
	var grid = document.getElementById('trx-ad-gallery-grid');
	var idsInput = document.getElementById('trx-ad-gallery-ids');
	var emptyState = document.getElementById('trx-ad-gallery-empty');
	var galleryBadge = document.getElementById('trx-ad-gallery-count');
	var clearBtn = document.getElementById('trx-ad-gallery-clear');
	var addBtn = document.getElementById('trx-ad-gallery-add');

	function updateGalleryBadge() {
		var items = grid.querySelectorAll('.trx-ad-gallery-item');
		var ids = [];
		items.forEach(function (item) { ids.push(item.getAttribute('data-id')); });
		idsInput.value = ids.join(',');
		if (galleryBadge) {
			galleryBadge.textContent = ids.length;
			galleryBadge.style.display = ids.length > 0 ? '' : 'none';
		}
		emptyState.style.display = ids.length === 0 ? '' : 'none';
		clearBtn.style.display = ids.length === 0 ? 'none' : '';
	}

	if (typeof jQuery !== 'undefined' && jQuery.fn.sortable) {
		jQuery(grid).sortable({
			items: '.trx-ad-gallery-item',
			cursor: 'grabbing',
			opacity: 0.7,
			placeholder: 'trx-ad-gallery-item ui-sortable-placeholder',
			tolerance: 'pointer',
			update: function () { updateGalleryBadge(); }
		});
	}

	grid.addEventListener('click', function (e) {
		var btn = e.target.closest('.trx-ad-gallery-remove');
		if (btn) { btn.closest('.trx-ad-gallery-item').remove(); updateGalleryBadge(); }
	});

	clearBtn.addEventListener('click', function () {
		if (!confirm(i18n.confirmRemoveAll || 'Remove all gallery images?')) { return; }
		grid.innerHTML = '';
		updateGalleryBadge();
	});

	addBtn.addEventListener('click', function () {
		var frame = wp.media({
			title: i18n.selectImages || 'Select Vehicle Images',
			button: { text: i18n.addToGallery || 'Add to Gallery' },
			library: { type: 'image' },
			multiple: true
		});
		frame.on('select', function () {
			frame.state().get('selection').each(function (att) {
				var d = att.toJSON();
				if (grid.querySelector('[data-id="' + d.id + '"]')) { return; }
				var thumb = (d.sizes && d.sizes.thumbnail) ? d.sizes.thumbnail.url : d.url;
				var div = document.createElement('div');
				div.className = 'trx-ad-gallery-item';
				div.setAttribute('data-id', d.id);
				div.innerHTML = '<img src="' + thumb + '" alt="">'
					+ '<button type="button" class="trx-ad-gallery-remove" title="' + (i18n.remove || 'Remove') + '"><span class="dashicons dashicons-no-alt"></span></button>'
					+ '<span class="trx-ad-gallery-badge">' + (i18n.main || 'Main') + '</span>';
				grid.appendChild(div);
			});
			updateGalleryBadge();
		});
		frame.open();
	});

	/* ================================================================
	   Self-hosted Videos
	   ================================================================ */
	var selfList = document.getElementById('trx-ad-self-video-list');
	var selfIds = document.getElementById('trx-ad-self-video-ids');
	var videoBadge = document.getElementById('trx-ad-video-count');
	var extList = document.getElementById('trx-ad-ext-video-list');

	function updateVideoCount() {
		var c = selfList.querySelectorAll('.trx-ad-video-row').length + extList.querySelectorAll('.trx-ad-ext-video-row').length;
		if (videoBadge) { videoBadge.textContent = c; videoBadge.style.display = c > 0 ? '' : 'none'; }
	}

	function updateSelfIds() {
		var ids = [];
		selfList.querySelectorAll('.trx-ad-video-row').forEach(function (r) { ids.push(r.getAttribute('data-id')); });
		selfIds.value = ids.join(',');
		updateVideoCount();
	}

	selfList.addEventListener('click', function (e) {
		var btn = e.target.closest('.trx-ad-video-row-remove');
		if (btn) { btn.closest('.trx-ad-video-row').remove(); updateSelfIds(); }
	});

	document.getElementById('trx-ad-self-video-add').addEventListener('click', function () {
		var frame = wp.media({
			title: i18n.selectVideo || 'Select Video',
			button: { text: i18n.addVideo || 'Add Video' },
			library: { type: 'video' },
			multiple: true
		});
		frame.on('select', function () {
			frame.state().get('selection').each(function (att) {
				var d = att.toJSON();
				if (selfList.querySelector('[data-id="' + d.id + '"]')) { return; }
				var div = document.createElement('div');
				div.className = 'trx-ad-video-row';
				div.setAttribute('data-id', d.id);
				div.innerHTML = '<span class="dashicons dashicons-media-video"></span><span class="trx-ad-video-filename">' + d.filename + '</span>'
					+ '<button type="button" class="trx-ad-video-row-remove" title="' + (i18n.remove || 'Remove') + '"><span class="dashicons dashicons-no-alt"></span></button>';
				selfList.appendChild(div);
			});
			updateSelfIds();
		});
		frame.open();
	});

	/* ================================================================
	   External Videos
	   ================================================================ */
	document.getElementById('trx-ad-ext-video-add').addEventListener('click', function () {
		var row = document.createElement('div');
		row.className = 'trx-ad-ext-video-row';
		row.innerHTML = '<div class="trx-ad-ext-video-input-row">'
			+ '<input type="url" name="trx_ad_videos_external[]" value="" class="widefat trx-ad-ext-video-url" placeholder="' + (i18n.videoPlaceholder || 'https://www.youtube.com/watch?v=...') + '">'
			+ '<button type="button" class="trx-ad-ext-video-remove" title="' + (i18n.remove || 'Remove') + '"><span class="dashicons dashicons-no-alt"></span></button></div>'
			+ '<div class="trx-ad-video-embed-preview"></div>';
		extList.appendChild(row);
		row.querySelector('input').focus();
		updateVideoCount();
	});

	extList.addEventListener('click', function (e) {
		var btn = e.target.closest('.trx-ad-ext-video-remove');
		if (btn) { btn.closest('.trx-ad-ext-video-row').remove(); updateVideoCount(); }
	});

	var previewTimer = null;
	extList.addEventListener('input', function (e) {
		if (!e.target.classList.contains('trx-ad-ext-video-url')) { return; }
		var input = e.target;
		var preview = input.closest('.trx-ad-ext-video-row').querySelector('.trx-ad-video-embed-preview');
		clearTimeout(previewTimer);
		previewTimer = setTimeout(function () {
			var url = input.value.trim();
			if (!url) { preview.innerHTML = ''; return; }
			var yt = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
			if (yt) { preview.innerHTML = '<iframe width="360" height="203" src="https://www.youtube.com/embed/' + yt[1] + '" frameborder="0" allowfullscreen loading="lazy"></iframe>'; return; }
			var vm = url.match(/vimeo\.com\/(?:video\/)?(\d+)/);
			if (vm) { preview.innerHTML = '<iframe width="360" height="203" src="https://player.vimeo.com/video/' + vm[1] + '" frameborder="0" allowfullscreen loading="lazy"></iframe>'; return; }
			preview.innerHTML = '<a href="' + url + '" target="_blank" rel="noopener">' + url + '</a>';
		}, 500);
	});

	/* ================================================================
	   Make → Model cascade (native multi-selects — the taxonomy pickers
	   carry no third-party dropdown library)
	   ================================================================ */
	var makeSelect = document.getElementById('trx-ad-make-select');
	var modelSelect = document.getElementById('trx-ad-model-select');

	if (makeSelect && modelSelect) {
		var allModelOptions = [];
		Array.prototype.forEach.call(modelSelect.options, function (opt) {
			allModelOptions.push({
				value: opt.value,
				text: opt.text,
				make: parseInt(opt.getAttribute('data-make'), 10) || 0,
				selected: opt.selected
			});
		});

		var filterModels = function () {
			var makeIds = [];
			Array.prototype.forEach.call(makeSelect.options, function (opt) {
				var id = parseInt(opt.value, 10);
				if (opt.selected && id > 0) { makeIds.push(id); }
			});

			var currentModels = [];
			Array.prototype.forEach.call(modelSelect.options, function (opt) {
				if (opt.selected) { currentModels.push(opt.value); }
			});

			modelSelect.innerHTML = '';
			allModelOptions.forEach(function (opt) {
				if (makeIds.length === 0 || makeIds.indexOf(opt.make) !== -1) {
					var selected = currentModels.indexOf(String(opt.value)) !== -1;
					modelSelect.appendChild(new Option(opt.text, opt.value, false, selected));
				}
			});
		};

		makeSelect.addEventListener('change', filterModels);
	}
})();
