(function () {
	'use strict';
	if (!window.lens) { return; }

	// Add query
	var addBtn   = document.getElementById('lens-add-query');
	var input    = document.getElementById('lens-new-query');
	var tbody    = document.getElementById('lens-queries-tbody');
	var runAll   = document.getElementById('lens-run-all');
	var emptyEl  = document.querySelector('#lens-queries-table .lens-empty');

	function rowHtml(q) {
		return '<tr data-query-id="' + q.id + '">'
			+ '<td>' + escapeHtml(q.query) + '</td>'
			+ '<td><span class="lens-pill ok">Active</span></td>'
			+ '<td class="muted">' + escapeHtml(q.created_at) + '</td>'
			+ '<td>'
				+ '<button type="button" class="lens-btn ghost lens-run-query"><span class="spinner"></span>Check now</button>'
				+ '<button type="button" class="lens-btn ghost lens-delete-query" style="color:#b32d2e;">Delete</button>'
			+ '</td></tr>';
	}

	if (addBtn) {
		addBtn.addEventListener('click', function () {
			var query = (input.value || '').trim();
			if (!query) { lens.toast('Type a query first.', 'warn'); return; }
			lens.busy(addBtn, true);
			lens.api('add_query', { query: query }).then(function (q) {
				if (emptyEl) { emptyEl.outerHTML = '<table class="lens-table"><thead><tr><th>Query</th><th>Status</th><th>Created</th><th></th></tr></thead><tbody id="lens-queries-tbody">' + rowHtml(q) + '</tbody></table>'; }
				else if (tbody) { tbody.insertAdjacentHTML('afterbegin', rowHtml(q)); }
				input.value = '';
				lens.toast(lens.i18n.queryAdded || 'Query added.', 'ok');
			}).catch(function (e) {
				lens.toast(e.message, 'bad');
			}).finally(function () {
				lens.busy(addBtn, false);
			});
		});
	}

	// Run-all
	if (runAll) {
		runAll.addEventListener('click', function () {
			lens.busy(runAll, true);
			runAll.textContent = (lens.i18n.running || 'Running…');
			var spin = document.createElement('span'); spin.className = 'spinner'; runAll.insertBefore(spin, runAll.firstChild);
			lens.api('run_all_citations', {}).then(function (data) {
				lens.toast('Ran ' + data.ran + ' check' + (data.ran === 1 ? '' : 's') + ' · cited in ' + data.cited + '.', 'ok');
				setTimeout(function () { window.location.reload(); }, 1200);
			}).catch(function (e) {
				lens.toast(e.message, 'bad');
				lens.busy(runAll, false);
				runAll.innerHTML = '<span class="spinner"></span>Run all';
			});
		});
	}

	// Per-row run + delete (event delegation)
	document.addEventListener('click', function (e) {
		var target = e.target.closest('.lens-run-query, .lens-delete-query');
		if (!target) { return; }
		var row = target.closest('[data-query-id]');
		if (!row) { return; }
		var id  = parseInt(row.dataset.queryId, 10);

		if (target.classList.contains('lens-run-query')) {
			lens.busy(target, true);
			lens.api('run_citation', { id: id }).then(function (r) {
				lens.toast(r.cited ? 'Cited at position ' + r.position + '.' : 'Not cited this time.', r.cited ? 'ok' : 'warn');
			}).catch(function (err) {
				lens.toast(err.message, 'bad');
			}).finally(function () { lens.busy(target, false); });
		} else if (target.classList.contains('lens-delete-query')) {
			if (!lens.confirm(lens.i18n.confirmDelete || 'Delete this query?')) { return; }
			lens.api('delete_query', { id: id }).then(function () {
				row.style.transition = 'opacity .2s';
				row.style.opacity = '0';
				setTimeout(function () { row.parentNode.removeChild(row); }, 200);
				lens.toast(lens.i18n.queryDeleted || 'Query removed.', 'ok');
			}).catch(function (e) {
				lens.toast(e.message, 'bad');
			});
		}
	});

	// Citation-rate chart
	var ctx = document.getElementById('lens-chart-citations');
	var chart = null;
	function loadChart(days) {
		if (!ctx || typeof window.Chart === 'undefined') { return; }
		lens.api('citations_data', { days: days }).then(function (data) {
			var palette = { 'openai': '#10a37f', 'perplexity': '#1da7be', 'gemini': '#4f46e5', 'claude': '#cc785c' };
			var datasets = (data.series || []).map(function (s) {
				return {
					label: s.label,
					data: s.data,
					borderColor: palette[s.label] || '#646970',
					backgroundColor: palette[s.label] || '#646970',
					tension: 0.3,
					spanGaps: true,
				};
			});
			if (chart) {
				chart.data.labels = data.days;
				chart.data.datasets = datasets;
				chart.update();
				return;
			}
			chart = new window.Chart(ctx, {
				type: 'line',
				data: { labels: data.days, datasets: datasets },
				options: {
					responsive: true, maintainAspectRatio: false,
					interaction: { mode: 'index', intersect: false },
					plugins: { legend: { position: 'bottom' } },
					scales: { y: { beginAtZero: true, max: 100, ticks: { callback: function (v) { return v + '%'; } } } }
				}
			});
		});
	}
	document.addEventListener('DOMContentLoaded', function () {
		loadChart(90);
		var sel = document.getElementById('lens-cite-range');
		if (sel) { sel.addEventListener('change', function () { loadChart(parseInt(sel.value, 10) || 90); }); }
	});

	function escapeHtml(s) {
		return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
			return { '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c];
		});
	}
})();
