(function () {
	'use strict';
	if (!window.lens || typeof window.Chart === 'undefined') { return; }

	var FAMILY_COLORS = {
		'OpenAI':      '#10a37f',
		'Anthropic':   '#cc785c',
		'Perplexity':  '#1da7be',
		'Google':      '#ea4335',
		'Microsoft':   '#0078d4',
		'Meta':        '#1877f2',
		'DeepSeek':    '#4f46e5',
		'Apple':       '#374151',
		'CommonCrawl': '#f59e0b',
		'Mistral':     '#a855f7',
	};

	function familyColor(name) {
		return FAMILY_COLORS[name] || '#646970';
	}

	var visitsChart = null;
	var familyChart = null;

	function el(id) { return document.getElementById(id); }

	function setKpi(name, value, windowLabel) {
		var card = document.querySelector('[data-kpi="' + name + '"]');
		if (!card) { return; }
		var v = card.querySelector('[data-value]');
		if (v) { v.textContent = value; }
		if (windowLabel) {
			var w = card.querySelector('[data-window]');
			if (w) { w.textContent = windowLabel; }
		}
	}

	function formatNumber(n) {
		if (n === null || n === undefined) { return '—'; }
		return new Intl.NumberFormat().format(n);
	}

	function load(days) {
		days = days || 30;
		lens.api('dashboard_data', { days: days }).then(function (data) {
			renderKpis(data, days);
			renderVisits(data);
			renderFamilies(data);
			renderTopPages(data);
			renderBlindSpots(data);
		}).catch(function (e) {
			lens.toast('Could not load dashboard data: ' + e.message, 'bad');
		});
	}

	function renderKpis(data, days) {
		setKpi('visits', formatNumber(data.total_visits), 'last ' + days + ' days');
		setKpi('families', formatNumber(Object.keys(data.totals_by_family || {}).length));
		setKpi('citation_rate', (data.citation_rate || 0) + '%');
		setKpi('blind_spots', formatNumber((data.blind_spots || []).length));
	}

	function renderVisits(data) {
		var ctx = el('lens-chart-visits');
		if (!ctx) { return; }

		var datasets = (data.series || []).map(function (s, i) {
			var color = familyColor(s.label);
			return {
				label: s.label,
				data: s.data,
				backgroundColor: color,
				borderColor: color,
				borderWidth: 1,
				stack: 'all',
			};
		});

		if (visitsChart) {
			visitsChart.data.labels = data.days;
			visitsChart.data.datasets = datasets;
			visitsChart.update();
			return;
		}
		visitsChart = new window.Chart(ctx, {
			type: 'bar',
			data: { labels: data.days, datasets: datasets },
			options: {
				responsive: true,
				maintainAspectRatio: false,
				interaction: { mode: 'index', intersect: false },
				plugins: {
					legend: { position: 'bottom', labels: { boxWidth: 10, padding: 12 } },
					tooltip: { callbacks: { footer: function (items) {
						var total = items.reduce(function (s, i) { return s + i.parsed.y; }, 0);
						return 'Total: ' + formatNumber(total);
					} } }
				},
				scales: {
					x: { stacked: true, grid: { display: false } },
					y: { stacked: true, beginAtZero: true, ticks: { precision: 0 } }
				}
			}
		});
	}

	function renderFamilies(data) {
		var ctx = el('lens-chart-families');
		if (!ctx) { return; }

		var entries = Object.entries(data.totals_by_family || {}).sort(function (a, b) { return b[1] - a[1]; });
		var labels  = entries.map(function (e) { return e[0]; });
		var values  = entries.map(function (e) { return e[1]; });
		var colors  = labels.map(familyColor);

		if (familyChart) {
			familyChart.data.labels = labels;
			familyChart.data.datasets[0].data = values;
			familyChart.data.datasets[0].backgroundColor = colors;
			familyChart.update();
			return;
		}
		familyChart = new window.Chart(ctx, {
			type: 'doughnut',
			data: { labels: labels, datasets: [{ data: values, backgroundColor: colors, borderWidth: 2, borderColor: '#fff' }] },
			options: {
				responsive: true,
				maintainAspectRatio: false,
				cutout: '60%',
				plugins: {
					legend: { position: 'bottom', labels: { boxWidth: 10, padding: 10, font: { size: 11 } } },
					tooltip: { callbacks: { label: function (ctx) {
						var total = ctx.dataset.data.reduce(function (s, v) { return s + v; }, 0);
						var pct   = total ? ((ctx.parsed / total) * 100).toFixed(1) : 0;
						return ctx.label + ': ' + formatNumber(ctx.parsed) + ' (' + pct + '%)';
					} } }
				}
			}
		});
	}

	function renderTopPages(data) {
		var container = el('lens-top-pages');
		if (!container) { return; }
		var rows = data.top_pages || [];
		if (!rows.length) {
			container.innerHTML = '<div class="lens-empty"><h3>No data yet</h3><p>AI bots crawl new sites slowly. Check back in 24-48 hours.</p></div>';
			return;
		}
		var max = rows[0].visits || 1;
		var html = '<table class="lens-table"><thead><tr><th>URI</th><th class="num">Visits</th><th style="width:30%">Share</th></tr></thead><tbody>';
		rows.forEach(function (r) {
			var pct = (r.visits / max) * 100;
			html += '<tr>'
				+ '<td class="mono">' + escapeHtml(r.request_uri) + '</td>'
				+ '<td class="num">' + formatNumber(r.visits) + '</td>'
				+ '<td><div style="background:#e6efff;border-radius:3px;height:8px;overflow:hidden;"><div style="background:#2271b1;height:100%;width:' + pct.toFixed(1) + '%"></div></div></td>'
				+ '</tr>';
		});
		html += '</tbody></table>';
		container.innerHTML = html;
	}

	function renderBlindSpots(data) {
		var container = el('lens-blind-spots');
		if (!container) { return; }
		var rows = data.blind_spots || [];
		if (!rows.length) {
			container.innerHTML = '<div class="lens-empty" style="padding:24px 8px;"><h3 style="margin:0 0 4px;font-size:14px;">All covered 🎉</h3><p style="font-size:12px;margin:0;">Every published post has been visited.</p></div>';
			return;
		}
		var html = '<ul style="list-style:none;margin:0;padding:0;">';
		rows.slice(0, 6).forEach(function (r) {
			html += '<li style="padding:8px 0;border-bottom:1px solid #f0f0f1;"><div style="font-weight:500;color:#1d2327;font-size:13px;">' + escapeHtml(r.post_title) + '</div><div style="color:#646970;font-size:11px;">' + escapeHtml(r.post_type) + ' · ' + escapeHtml(r.post_modified_gmt) + '</div></li>';
		});
		html += '</ul>';
		container.innerHTML = html;
	}

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

	document.addEventListener('DOMContentLoaded', function () {
		load(30);
		var rangeSel = el('lens-range');
		if (rangeSel) {
			rangeSel.addEventListener('change', function () { load(parseInt(rangeSel.value, 10) || 30); });
		}
	});
})();
