/**
 * Lens — AI Visibility Monitor — main admin JS.
 *
 * Provides:
 *   - lens.toast(message, kind)        Toast notifications (kind: 'ok'|'bad'|'warn'|'info')
 *   - lens.api(action, data, opts)     Promise-returning POST to admin-ajax with nonce
 *   - lens.postPicker(input)           Wire a search-as-you-type post picker
 *   - lens.scoreClass(n)               'high' | 'mid' | 'low' colour mapping
 */
(function () {
	'use strict';

	if (typeof window.lensConfig === 'undefined') {
		// Config is localised from PHP. If missing, bail.
		window.lensConfig = { ajaxUrl: window.ajaxurl || '/wp-admin/admin-ajax.php', nonce: '', i18n: {} };
	}

	var cfg = window.lensConfig;
	var i18n = cfg.i18n || {};

	// ---------- Toast notifications -------------------------------------

	function ensureToastContainer() {
		var el = document.getElementById('lens-toasts');
		if (el) { return el; }
		el = document.createElement('div');
		el.id = 'lens-toasts';
		el.className = 'lens-toasts';
		el.setAttribute('role', 'status');
		el.setAttribute('aria-live', 'polite');
		document.body.appendChild(el);
		return el;
	}

	function toast(message, kind) {
		kind = kind || 'info';
		var container = ensureToastContainer();
		var el = document.createElement('div');
		el.className = 'lens-toast ' + kind;
		el.innerHTML = '';
		var msg = document.createElement('div');
		msg.textContent = message;
		var close = document.createElement('button');
		close.type = 'button';
		close.className = 'close';
		close.setAttribute('aria-label', i18n.close || 'Dismiss');
		close.innerHTML = '×';
		close.addEventListener('click', function () { dismiss(el); });
		el.appendChild(msg);
		el.appendChild(close);
		container.appendChild(el);
		setTimeout(function () { dismiss(el); }, 5000);
	}

	function dismiss(el) {
		if (!el.parentNode) { return; }
		el.classList.add('fade-out');
		setTimeout(function () { if (el.parentNode) { el.parentNode.removeChild(el); } }, 250);
	}

	// ---------- AJAX wrapper --------------------------------------------

	function api(action, data, opts) {
		opts = opts || {};
		var body = new URLSearchParams();
		body.append('action', 'lens_' + action);
		body.append('_wpnonce', cfg.nonce);
		if (data) {
			Object.keys(data).forEach(function (k) {
				var v = data[k];
				if (Array.isArray(v)) {
					v.forEach(function (item) { body.append(k + '[]', item); });
				} else if (v !== null && v !== undefined) {
					body.append(k, v);
				}
			});
		}

		return fetch(cfg.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			body: body.toString()
		}).then(function (r) {
			if (!r.ok) {
				return r.text().then(function (text) {
					throw new Error('HTTP ' + r.status + ': ' + (text || r.statusText));
				});
			}
			return r.json();
		}).then(function (json) {
			if (json && json.success === false) {
				var msg = (json.data && json.data.message) || (i18n.errorGeneric || 'Something went wrong.');
				var err = new Error(msg);
				err.code = json.data && json.data.code;
				throw err;
			}
			return json && json.data ? json.data : json;
		});
	}

	// ---------- Score colouring -----------------------------------------

	function scoreClass(n) {
		if (n === null || n === undefined) { return ''; }
		var v = parseInt(n, 10) || 0;
		if (v >= 75) { return 's-high'; }
		if (v >= 50) { return 's-mid'; }
		return 's-low';
	}

	// ---------- Post picker ---------------------------------------------

	function postPicker(input, options) {
		options = options || {};
		var wrap = input.closest('.lens-picker');
		if (!wrap) { return; }
		var results = wrap.querySelector('.lens-picker-results');
		var hidden  = wrap.querySelector('input[type=hidden]');
		var timeout = null;
		var activeIndex = -1;

		function doSearch(term) {
			if (!term || term.length < 2) {
				results.innerHTML = '';
				wrap.classList.remove('open');
				return;
			}
			api('search_posts', { term: term }).then(function (data) {
				renderResults(data && data.items ? data.items : []);
			}).catch(function (e) {
				renderResults([], e.message);
			});
		}

		function renderResults(items, errorMsg) {
			activeIndex = -1;
			results.innerHTML = '';
			if (errorMsg) {
				var msg = document.createElement('div');
				msg.className = 'lens-picker-empty';
				msg.textContent = errorMsg;
				results.appendChild(msg);
				wrap.classList.add('open');
				return;
			}
			if (!items.length) {
				var empty = document.createElement('div');
				empty.className = 'lens-picker-empty';
				empty.textContent = i18n.noResults || 'No results.';
				results.appendChild(empty);
				wrap.classList.add('open');
				return;
			}
			items.forEach(function (item) {
				var row = document.createElement('div');
				row.className = 'result';
				row.dataset.id = item.id;
				row.dataset.title = item.title;
				row.innerHTML = '';
				var t = document.createElement('div');
				t.className = 'title';
				t.textContent = item.title;
				var m = document.createElement('div');
				m.className = 'meta';
				m.textContent = '#' + item.id + ' · ' + item.post_type + (item.status === 'publish' ? '' : ' · ' + item.status);
				row.appendChild(t);
				row.appendChild(m);
				row.addEventListener('mousedown', function (e) {
					e.preventDefault();
					select(row);
				});
				results.appendChild(row);
			});
			wrap.classList.add('open');
		}

		function select(row) {
			if (hidden) { hidden.value = row.dataset.id; }
			input.value = row.dataset.title;
			wrap.classList.remove('open');
			if (typeof options.onSelect === 'function') {
				options.onSelect({ id: parseInt(row.dataset.id, 10), title: row.dataset.title });
			}
		}

		input.addEventListener('input', function () {
			if (hidden) { hidden.value = ''; }
			clearTimeout(timeout);
			timeout = setTimeout(function () { doSearch(input.value.trim()); }, 200);
		});

		input.addEventListener('focus', function () {
			if (input.value.length >= 2) { wrap.classList.add('open'); }
		});

		input.addEventListener('blur', function () {
			setTimeout(function () { wrap.classList.remove('open'); }, 150);
		});

		input.addEventListener('keydown', function (e) {
			var rows = results.querySelectorAll('.result');
			if (e.key === 'ArrowDown' && rows.length) {
				e.preventDefault();
				activeIndex = (activeIndex + 1) % rows.length;
				updateActive(rows);
			} else if (e.key === 'ArrowUp' && rows.length) {
				e.preventDefault();
				activeIndex = activeIndex <= 0 ? rows.length - 1 : activeIndex - 1;
				updateActive(rows);
			} else if (e.key === 'Enter' && activeIndex >= 0 && rows[activeIndex]) {
				e.preventDefault();
				select(rows[activeIndex]);
			} else if (e.key === 'Escape') {
				wrap.classList.remove('open');
			}
		});

		function updateActive(rows) {
			rows.forEach(function (r, i) { r.classList.toggle('active', i === activeIndex); });
			if (activeIndex >= 0 && rows[activeIndex]) {
				rows[activeIndex].scrollIntoView({ block: 'nearest' });
			}
		}
	}

	// ---------- Button helpers ------------------------------------------

	function busy(btn, on) {
		if (!btn) { return; }
		btn.setAttribute('aria-busy', on ? 'true' : 'false');
		btn.disabled = !!on;
		if (on && !btn.querySelector('.spinner')) {
			var s = document.createElement('span');
			s.className = 'spinner';
			s.setAttribute('aria-hidden', 'true');
			btn.insertBefore(s, btn.firstChild);
		}
	}

	// ---------- Confirm dialog (uses native confirm but wrapped) --------

	function confirmAction(message) {
		return window.confirm(message);
	}

	// ---------- Public API ----------------------------------------------

	window.lens = {
		toast: toast,
		api: api,
		postPicker: postPicker,
		scoreClass: scoreClass,
		busy: busy,
		confirm: confirmAction,
		i18n: i18n
	};

	// Wire up any .lens-picker elements on page-load
	document.addEventListener('DOMContentLoaded', function () {
		document.querySelectorAll('.lens-picker input[type=search], .lens-picker input.lens-picker-input').forEach(function (input) {
			postPicker(input);
		});
	});
})();
