/**
 * Taxonomy icon picker — modal icon selection + custom image upload.
 *
 * @package ThemeREX\AutoDealer
 */
(function () {
	'use strict';

	var activeWrapper = null;
	var modal = null;
	var modalPicker = null;
	var modalUpload = null;

	// Build the shared modal once.
	function ensureModal() {
		if (modal) return;

		modal = document.createElement('div');
		modal.className = 'trx-ad-icon-modal-overlay';
		modal.innerHTML =
			'<div class="trx-ad-icon-modal">' +
				'<div class="trx-ad-icon-modal__header">' +
					'<h3>' + (trxAdIconPicker.title || 'Choose Icon') + '</h3>' +
					'<button type="button" class="trx-ad-icon-modal__close">&times;</button>' +
				'</div>' +
				'<div class="trx-ad-icon-modal__body">' +
					'<div class="trx-ad-icon-picker" id="trx-ad-modal-picker"></div>' +
				'</div>' +
				'<div class="trx-ad-icon-modal__footer">' +
					'<div class="trx-ad-icon-upload" id="trx-ad-modal-upload">' +
						'<button type="button" class="button trx-ad-icon-upload__btn"' +
							' data-title="' + (trxAdIconPicker.uploadTitle || 'Select Icon') + '"' +
							' data-button-text="' + (trxAdIconPicker.uploadButton || 'Use as Icon') + '">' +
							(trxAdIconPicker.uploadLabel || 'Upload Custom Image') +
						'</button>' +
						'<span class="trx-ad-icon-upload__preview" style="margin-left:10px;"></span>' +
					'</div>' +
					'<button type="button" class="button button-primary trx-ad-icon-modal__done">' +
						(trxAdIconPicker.done || 'Done') +
					'</button>' +
				'</div>' +
			'</div>';

		document.body.appendChild(modal);

		modalPicker = modal.querySelector('#trx-ad-modal-picker');
		modalUpload = modal.querySelector('#trx-ad-modal-upload');

		// Close modal.
		modal.querySelector('.trx-ad-icon-modal__close').addEventListener('click', closeModal);
		modal.querySelector('.trx-ad-icon-modal__done').addEventListener('click', closeModal);
		modal.addEventListener('click', function (e) {
			if (e.target === modal) closeModal();
		});

		// Icon selection inside modal.
		modalPicker.addEventListener('click', function (e) {
			var item = e.target.closest('.trx-ad-icon-picker__item');
			if (!item) return;

			modalPicker.querySelectorAll('.trx-ad-icon-picker__item').forEach(function (el) {
				el.classList.remove('trx-ad-icon-picker__item--selected');
			});
			item.classList.add('trx-ad-icon-picker__item--selected');

			if (!activeWrapper) return;
			var value = item.dataset.icon || '';
			activeWrapper.querySelector('.trx-ad-icon-picker__input').value = value;

			// Clear custom image when an icon is selected.
			if (value) {
				activeWrapper.querySelector('.trx-ad-icon-upload__input').value = '';
				var preview = modalUpload.querySelector('.trx-ad-icon-upload__preview');
				preview.innerHTML = '';
			}

			updateTriggerPreview(activeWrapper);
		});

		// Upload inside modal.
		modalUpload.querySelector('.trx-ad-icon-upload__btn').addEventListener('click', function (e) {
			e.preventDefault();
			if (!activeWrapper) return;

			var btn = this;
			var frame = wp.media({
				title: btn.dataset.title || 'Select Icon',
				button: { text: btn.dataset.buttonText || 'Use as Icon' },
				multiple: false,
				library: { type: ['image', 'image/svg+xml'] }
			});

			frame.on('select', function () {
				var attachment = frame.state().get('selection').first().toJSON();
				var imgUrl = attachment.sizes && attachment.sizes.thumbnail
					? attachment.sizes.thumbnail.url
					: attachment.url;

				activeWrapper.querySelector('.trx-ad-icon-upload__input').value = attachment.id;

				// Clear icon selection.
				activeWrapper.querySelector('.trx-ad-icon-picker__input').value = '';
				modalPicker.querySelectorAll('.trx-ad-icon-picker__item').forEach(function (el) {
					el.classList.remove('trx-ad-icon-picker__item--selected');
				});
				var noneItem = modalPicker.querySelector('[data-icon=""]');
				if (noneItem) noneItem.classList.add('trx-ad-icon-picker__item--selected');

				var preview = modalUpload.querySelector('.trx-ad-icon-upload__preview');
				preview.innerHTML =
					'<img src="' + imgUrl + '" alt="">' +
					'<span class="trx-ad-icon-upload__remove">&times;</span>';

				updateTriggerPreview(activeWrapper);
			});

			frame.open();
		});

		// Remove uploaded image inside modal.
		modalUpload.addEventListener('click', function (e) {
			if (!e.target.classList.contains('trx-ad-icon-upload__remove')) return;
			if (!activeWrapper) return;

			activeWrapper.querySelector('.trx-ad-icon-upload__input').value = '';
			modalUpload.querySelector('.trx-ad-icon-upload__preview').innerHTML = '';
			updateTriggerPreview(activeWrapper);
		});
	}

	function openModal(wrapper) {
		ensureModal();
		activeWrapper = wrapper;

		// Clone the icon grid from the wrapper's hidden picker into the modal.
		var sourcePicker = wrapper.querySelector('.trx-ad-icon-picker');
		modalPicker.innerHTML = sourcePicker.innerHTML;

		// Sync selected state.
		var currentIcon = wrapper.querySelector('.trx-ad-icon-picker__input').value;
		modalPicker.querySelectorAll('.trx-ad-icon-picker__item').forEach(function (el) {
			el.classList.toggle('trx-ad-icon-picker__item--selected', el.dataset.icon === currentIcon);
		});

		// Sync upload preview.
		var imageId = wrapper.querySelector('.trx-ad-icon-upload__input').value;
		var sourcePreview = wrapper.querySelector('.trx-ad-icon-upload__preview');
		var modalPreview = modalUpload.querySelector('.trx-ad-icon-upload__preview');
		modalPreview.innerHTML = sourcePreview.innerHTML;

		modal.classList.add('trx-ad-icon-modal-overlay--open');
	}

	function closeModal() {
		if (!modal) return;
		modal.classList.remove('trx-ad-icon-modal-overlay--open');

		// Sync modal upload preview back to wrapper.
		if (activeWrapper) {
			var modalPreview = modalUpload.querySelector('.trx-ad-icon-upload__preview');
			var wrapperPreview = activeWrapper.querySelector('.trx-ad-icon-upload__preview');
			wrapperPreview.innerHTML = modalPreview.innerHTML;
		}

		activeWrapper = null;
	}

	function updateTriggerPreview(wrapper) {
		var trigger = wrapper.querySelector('.trx-ad-icon-trigger__preview');
		if (!trigger) return;

		var imageId = wrapper.querySelector('.trx-ad-icon-upload__input').value;
		var icon = wrapper.querySelector('.trx-ad-icon-picker__input').value;

		if (imageId) {
			// Show uploaded image preview from the modal upload preview.
			var imgEl = modalUpload.querySelector('.trx-ad-icon-upload__preview img');
			if (imgEl) {
				trigger.innerHTML = '<img src="' + imgEl.src + '" alt="">';
				return;
			}
		}

		if (icon) {
			// Copy the SVG from the selected modal item.
			var selected = modalPicker.querySelector('[data-icon="' + icon + '"]');
			if (selected) {
				trigger.innerHTML = selected.innerHTML;
				return;
			}
		}

		trigger.innerHTML = '<span style="color:#999;">—</span>';
	}

	// Open modal on trigger click.
	document.addEventListener('click', function (e) {
		var trigger = e.target.closest('.trx-ad-icon-trigger');
		if (!trigger) return;

		var wrapper = trigger.closest('.trx-ad-icon-wrapper');
		if (wrapper) openModal(wrapper);
	});

	// Close on Escape.
	document.addEventListener('keydown', function (e) {
		if (e.key === 'Escape' && modal && modal.classList.contains('trx-ad-icon-modal-overlay--open')) {
			closeModal();
		}
	});
})();