/**
 * Niwa AI - Admin Settings interactions.
 *
 * Handles:
 * - auth mode dependent model list updates
 * - backend/frontend avatar selection through the WordPress media library
 */
(function () {
	'use strict';

	var config = window.niwaAdminSettings || {};
	var mediaFrames = {};

	function getAdminWidget() {
		return document.querySelector('.niwa-widget--admin');
	}

	function setAdminWidgetSuppressed(isSuppressed) {
		var widget = getAdminWidget();
		if (!widget) return;

		widget.classList.toggle('niwa-widget--suppressed', !!isSuppressed);
		log('Admin widget suppression toggled.', {
			suppressed: !!isSuppressed
		});
	}

	function log() {
		if (!window.console || !window.console.log) return;
		var args = Array.prototype.slice.call(arguments);
		args.unshift('[Niwa Admin Settings]');
		window.console.log.apply(window.console, args);
	}

	function warn() {
		if (!window.console || !window.console.warn) return;
		var args = Array.prototype.slice.call(arguments);
		args.unshift('[Niwa Admin Settings]');
		window.console.warn.apply(window.console, args);
	}

	function getById(id) {
		return id ? document.getElementById(id) : null;
	}

	function updateAvatarPreview(input, previewId, fallbackUrl) {
		if (!input || !previewId) return;

		var preview = getById(previewId);
		if (!preview) return;

		var url = (input.value || '').trim() || fallbackUrl || '';
		preview.innerHTML = url
			? '<img src="' + url.replace(/"/g, '&quot;') + '" alt="" style="width:64px;height:64px;object-fit:cover;border-radius:999px;border:1px solid rgba(15,23,42,0.08);background:#fff;display:block;" />'
			: '';
	}

	function toggleRemoveButton(targetId) {
		var input = getById(targetId);
		var removeBtn = document.querySelector('[data-niwa-remove-target="' + targetId + '"]');
		if (!removeBtn || !input) return;
		removeBtn.style.display = (input.value || '').trim() ? '' : 'none';
	}

	function initModeSwitcher() {
		var modeSelect = getById('niwa-auth-mode');
		var generalForm = getById('niwa-general-form');
		var modelSelect = getById('niwa-chat-model');
		var dirtyHint = getById('niwa-general-auth-dirty-hint');
		var saveGeneral = generalForm ? generalForm.querySelector('[type="submit"]') : null;
		if (!modeSelect || !generalForm || !modelSelect) return;

		var initialMode = modeSelect.value;
		function syncGeneralLock() {
			var locked = modeSelect.value !== initialMode;
			modelSelect.disabled = locked;
			if (saveGeneral) saveGeneral.disabled = locked;
			if (dirtyHint) dirtyHint.hidden = !locked;
		}

		modeSelect.addEventListener('change', syncGeneralLock);
		generalForm.addEventListener('submit', function (event) {
			if (modeSelect.value !== initialMode) {
				event.preventDefault();
				syncGeneralLock();
			}
		});
	}

	function openMediaFrame(button) {
		if (!button) return;

		var targetId = button.getAttribute('data-niwa-media-target');
		var previewId = button.getAttribute('data-niwa-preview-target');
		var input = getById(targetId);
		var removeBtn = document.querySelector('[data-niwa-remove-target="' + targetId + '"]');

		log('Choose Image clicked.', {
			targetId: targetId,
			previewId: previewId,
			hasInput: !!input,
			hasWp: !!window.wp,
			hasWpMedia: !!(window.wp && window.wp.media),
			assetVersion: config.assetVersion || ''
		});

		if (!input) {
			warn('Media target input not found for button.', targetId);
			return;
		}

		if (!window.wp || !window.wp.media) {
			warn('wp.media is unavailable when Choose Image was clicked.');
			window.alert('WordPress media library is not ready yet. Reload the page and try again.');
			return;
		}

		if (!mediaFrames[targetId]) {
			mediaFrames[targetId] = window.wp.media({
				title: 'Choose avatar image',
				button: { text: 'Use this image' },
				library: { type: 'image' },
				multiple: false
			});

			mediaFrames[targetId].on('open', function () {
				setAdminWidgetSuppressed(true);
				log('Media frame opened.', {
					targetId: targetId
				});
			});

			mediaFrames[targetId].on('select', function () {
				var selection = mediaFrames[targetId].state().get('selection');
				var attachment = selection && selection.first ? selection.first().toJSON() : null;

				log('Media selected.', {
					targetId: targetId,
					attachment: attachment
				});

				if (!attachment || !attachment.url) {
					warn('Selected media item is missing a URL.', attachment);
					return;
				}

				input.value = attachment.url;
				updateAvatarPreview(input, previewId, '');

				if (removeBtn) {
					removeBtn.style.display = '';
				}
			});

			mediaFrames[targetId].on('close', function () {
				setAdminWidgetSuppressed(false);
				log('Media frame closed.', {
					targetId: targetId
				});
			});
		}

		mediaFrames[targetId].open();
	}

	function removeMedia(button) {
		if (!button) return;

		var targetId = button.getAttribute('data-niwa-remove-target');
		var previewId = button.getAttribute('data-niwa-preview-target');
		var fallbackUrl = button.getAttribute('data-niwa-default-preview') || '';
		var input = getById(targetId);

		log('Remove avatar clicked.', {
			targetId: targetId,
			previewId: previewId
		});

		if (input) {
			input.value = '';
		}

		updateAvatarPreview(input, previewId, fallbackUrl);
		button.style.display = 'none';
	}

	function initMediaPicker() {
		var mediaButtons = document.querySelectorAll('[data-niwa-media-target]');
		var removeButtons = document.querySelectorAll('[data-niwa-remove-target]');

		log('Init media picker.', {
			assetVersion: config.assetVersion || '',
			mediaButtons: mediaButtons.length,
			removeButtons: removeButtons.length,
			hasWp: !!window.wp,
			hasWpMedia: !!(window.wp && window.wp.media)
		});

		document.addEventListener('click', function (event) {
			var mediaButton = event.target && event.target.closest
				? event.target.closest('[data-niwa-media-target]')
				: null;
			if (mediaButton) {
				event.preventDefault();
				openMediaFrame(mediaButton);
				return;
			}

			var removeButton = event.target && event.target.closest
				? event.target.closest('[data-niwa-remove-target]')
				: null;
			if (removeButton) {
				event.preventDefault();
				removeMedia(removeButton);
			}
		});

		document.addEventListener('input', function (event) {
			var target = event.target;
			if (!target || !target.id || !/^niwa_(frontend|backend)_avatar_url$/.test(target.id)) return;

			var previewId = target.id + '_preview';
			updateAvatarPreview(target, previewId, '');
			toggleRemoveButton(target.id);
			log('Avatar input changed manually.', {
				targetId: target.id,
				valueLength: (target.value || '').length
			});
		});
	}

	function init() {
		log('Script booted.', {
			assetVersion: config.assetVersion || '',
			readyState: document.readyState
		});
		initModeSwitcher();
		initMediaPicker();
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
})();
