(function () {
	if (typeof truebeChat === 'undefined') { return; }
	var cfg = truebeChat;
	var ajax = cfg.ajax;
	var viewDoc = cfg.viewDoc;
	var nonce = cfg.nonce;
	var greeting = cfg.greeting;
	var ACCENT = cfg.accent;
	var BOT = cfg.bot;
	var FB = cfg.fallback;

	var log = document.getElementById('tb-chat-log');
	var input = document.getElementById('tb-chat-input');
	var send = document.getElementById('tb-chat-send');
	var docSel = document.getElementById('tb-chat-doc');
	if (!log || !input || !send) { return; }
	var inFlight = false;

	function hx(h){ h = h.replace('#',''); return [parseInt(h.substr(0,2),16), parseInt(h.substr(2,2),16), parseInt(h.substr(4,2),16)]; }
	function toHex(r,g,b){ return '#' + [r,g,b].map(function(v){ return ('0' + Math.round(v).toString(16)).slice(-2); }).join(''); }
	function mix(a,b,t){ var x = hx(a), y = hx(b); return toHex(x[0]+(y[0]-x[0])*t, x[1]+(y[1]-x[1])*t, x[2]+(y[2]-x[2])*t); }
	function lum(h){ var c = hx(h).map(function(v){ v /= 255; return v <= .03928 ? v/12.92 : Math.pow((v+.055)/1.055, 2.4); }); return .2126*c[0] + .7152*c[1] + .0722*c[2]; }
	function ink(bg){ return lum(bg) > .5 ? '#1d2327' : '#ffffff'; }

	function cleanDoc(name){ name = String(name || ''); var m = name.match(/^[a-f0-9]+\.[0-9]+_(.+)$/i); return m ? m[1] : name; }

	function citationPlain(s){ var parts = [cleanDoc(s.doc)]; if (s.section){ parts.push(s.section); } if (s.heading){ parts.push(s.heading); } if (s.page){ parts.push('page ' + s.page); } return parts.join(' \u203a '); }

	/* Copy that works on http (LocalWP) and https alike. */
	function copyText(text){
		if (navigator.clipboard && window.isSecureContext){
			return navigator.clipboard.writeText(text);
		}
		return new Promise(function(resolve, reject){
			var ta = document.createElement('textarea');
			ta.value = text;
			ta.style.cssText = 'position:fixed;top:-1000px;opacity:0;';
			document.body.appendChild(ta);
			ta.focus();
			ta.select();
			try {
				document.execCommand('copy') ? resolve() : reject();
			} catch (e) {
				reject(e);
			}
			document.body.removeChild(ta);
		});
	}

	function userBubble(text){
		var b = document.createElement('div');
		b.className = 'truebe-ap-bub truebe-ap-user';
		b.style.background = mix(ACCENT, '#ffffff', .86);
		b.style.color = mix(ACCENT, '#000000', .15);
		b.textContent = text;
		log.appendChild(b);
		log.scrollTop = log.scrollHeight;
		return b;
	}

	function botBubble(text, source, question){
		var b = document.createElement('div');
		b.className = 'truebe-ap-bub';
		b.style.background = BOT;
		b.style.color = ink(BOT);

		var body = document.createElement('div');
		body.textContent = text;
		b.appendChild(body);

		if (source && source.doc){
			var row = document.createElement('div');
			row.style.cssText = 'margin-top:8px;font-size:12px;opacity:0.85;display:flex;align-items:center;flex-wrap:wrap;gap:4px;';

			var lead = document.createElement('span');
			var bits = ['Source: ' + cleanDoc(source.doc)];
			if (source.section){ bits.push(source.section); }
			if (source.heading){ bits.push(source.heading); }
			lead.textContent = bits.join(' \u203a ');
			row.appendChild(lead);

			if (source.page){
				var sep = document.createElement('span'); sep.textContent = '\u203a'; row.appendChild(sep);
				var pageLink = document.createElement('a');
				pageLink.href = viewDoc + '?action=truebe_view_doc&doc=' + encodeURIComponent(source.doc) + '&_wpnonce=' + encodeURIComponent(cfg.viewDocNonce) + '#page=' + source.page;				
				pageLink.target = '_blank'; pageLink.rel = 'noopener';
				pageLink.textContent = 'page ' + source.page;
				pageLink.style.cssText = 'color:' + ACCENT + ';text-decoration:none;';
				row.appendChild(pageLink);
			}

			var copy = document.createElement('button');
			copy.type = 'button';
			copy.title = 'Copy question, answer, and source';
			copy.style.cssText = 'border:none;background:none;cursor:pointer;color:' + ACCENT + ';padding:0 2px;line-height:1;display:inline-flex;outline:none;box-shadow:none;';
			copy.addEventListener('focus', function(){ copy.style.outline = 'none'; copy.style.boxShadow = 'none'; });
			copy.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
			copy.addEventListener('click', function(){
				var out = '';
				if (question){ out += 'Q: ' + question + '\n\n'; }
				out += 'A: ' + text + '\n\nSource: ' + citationPlain(source);
				copyText(out).then(function(){
					var original = copy.innerHTML;
					copy.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>';
					setTimeout(function(){ copy.innerHTML = original; }, 1500);
				});
			});
			row.appendChild(copy);
			b.appendChild(row);
		}

		log.appendChild(b);
		log.scrollTop = log.scrollHeight;
		return b;
	}

	function fallbackBubble(title, sub, suggestions){
		var wrap = document.createElement('div');
		wrap.className = 'truebe-ap-fb';
		wrap.style.background = FB;
		var txt = ink(FB);
		wrap.style.color = txt;

		var t = document.createElement('div');
		t.className = 'truebe-ap-fbtitle';
		t.textContent = title;
		wrap.appendChild(t);

		if (sub){ var s = document.createElement('div'); s.className = 'truebe-ap-fbsub'; s.textContent = sub; wrap.appendChild(s); }

		if (suggestions && suggestions.length){
			var tile = mix(FB, '#000000', .07);
			suggestions.forEach(function(sg){
				var item = document.createElement('div');
				item.className = 'truebe-ap-fbitem';
				item.style.background = tile;
				item.style.color = txt;
				item.style.cursor = 'pointer';
				item.textContent = sg.label;
				item.addEventListener('click', function(){ ask(sg.label); });
				wrap.appendChild(item);
			});
		}

		log.appendChild(wrap);
		log.scrollTop = log.scrollHeight;
		return wrap;
	}

	function setBusy(state){ inFlight = state; input.disabled = state; send.style.opacity = state ? '0.5' : ''; send.style.cursor = state ? 'default' : 'pointer'; }

	function ask(q){
		if (inFlight){ return; }
		userBubble(q);
		input.value = '';
		setBusy(true);
		var thinking = botBubble('\u2026');
		var body = new URLSearchParams();
		body.append('action', 'truebe_chat_query');
		body.append('_ajax_nonce', nonce);
		body.append('query', q);
		body.append('context', 'internal');
		if (docSel && docSel.value){ body.append('doc', docSel.value); }
		fetch(ajax, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, credentials: 'same-origin', body: body.toString() })
			.then(function(r){ return r.json(); })
			.then(function(res){
				thinking.remove();
				if (!res || !res.success){ botBubble('Something went wrong. Please try again.'); return; }
				var d = res.data;
				if (d.status === 'inactive' || d.type === 'inactive'){
					botBubble('This assistant is not currently active.');
				} else if (d.type === 'answer' && d.thesis && d.thesis.trim()){
					botBubble(d.thesis, d.source_detail, q);
				} else if (d.suggestions && d.suggestions.length){
					fallbackBubble("We don't have an answer for that yet", 'You might find these helpful:', d.suggestions);
				} else {
					fallbackBubble("We don't have an answer for that yet", 'Your question has been logged so it can be answered.', null);
				}
			})
			.catch(function(){ thinking.remove(); botBubble('Something went wrong. Please try again.'); })
			.then(function(){ setBusy(false); input.focus(); });
	}

	if (greeting){ botBubble(greeting); }

	send.addEventListener('click', function(){ var q = input.value.trim(); if (q){ ask(q); } });
	input.addEventListener('keydown', function(e){ if (e.key === 'Enter'){ var q = input.value.trim(); if (q){ ask(q); } } });
	input.focus();
})();