(function(){
	/* Flash pill fade-out (shown after a delete) */
	var f = document.getElementById('truebe-flash');
	if (f){
		setTimeout(function(){
			f.style.opacity = '0';
			setTimeout(function(){ f.style.display = 'none'; }, 300);
		}, 2500);
		if (window.history && history.replaceState){
			var u = new URL(window.location);
			u.searchParams.delete('msg');
			history.replaceState({}, '', u);
		}
	}
})();

(function(){
	/* Delete confirmation, replacing the inline onsubmit handler */
	if (typeof truebeSeeds === 'undefined') { return; }
	var msg = truebeSeeds.confirmDelete || 'Are you sure you want to delete this question and answer?';
	document.querySelectorAll('form.truebe-delete-form').forEach(function(form){
		form.addEventListener('submit', function(e){
			if (!window.confirm(msg)){ e.preventDefault(); }
		});
	});
})();

(function(){
	/* Unanswered tab: gap answer/dismiss buttons, with live tab/badge/row updates */
	if (typeof truebeSeeds === 'undefined') { return; }
	var nonce = truebeSeeds.gapNonce, ajax = truebeSeeds.ajax;
	function reset(b){ b.disabled = false; b.style.opacity = '1'; b.style.cursor = 'pointer'; if (b.dataset.orig){ b.textContent = b.dataset.orig; } }
	function pick(b){ b.disabled = true; b.style.opacity = '0.6'; b.style.cursor = 'default'; if (!b.dataset.orig){ b.dataset.orig = b.textContent; } b.textContent = '\u2713 ' + b.dataset.orig; }

	var tabs = document.querySelectorAll('.truebe-tabs .truebe-tab');
	var unansweredTab = null, answersTab = null;
	tabs.forEach(function(t){
		if (/Unanswered/.test(t.textContent)) { unansweredTab = t; }
		else if (/Answers/.test(t.textContent)) { answersTab = t; }
	});

	function adjustBadge(tab, delta){
		if (!tab) { return; }
		var badge = tab.querySelector('.truebe-tab-badge');
		var current = badge ? parseInt(badge.textContent, 10) || 0 : 0;
		var next = current + delta;
		if (next <= 0){
			if (badge) { badge.remove(); }
			return;
		}
		if (!badge){
			badge = document.createElement('span');
			badge.className = 'truebe-tab-badge';
			tab.appendChild(badge);
		}
		badge.textContent = String(next);
	}

	function removeRow(row){
		var list = row.parentElement;
		row.remove();
		if (list && list.querySelectorAll('.truebe-gap-row').length === 0){
			var empty = document.createElement('div');
			empty.style.cssText = 'background:#fff;border:1px solid #dcdcde;border-radius:10px;padding:28px 32px;color:#646970;font-size:14px;';
			empty.textContent = "No unanswered questions yet. When a visitor asks something your chatbot can't answer, it shows up here.";
			list.appendChild(empty);
		}
	}

	document.querySelectorAll('.truebe-gap-row').forEach(function(row){
		var btns = row.querySelectorAll('.truebe-gap-btn');
		btns.forEach(function(btn){
			btn.addEventListener('click', function(){
				if (btn.disabled){ return; }
				var act = btn.getAttribute('data-gap-act'), gid = btn.getAttribute('data-gap-id'), q = btn.getAttribute('data-gap-q') || '';
				if ('dismiss' === act){
					var confirmMsg = truebeSeeds.confirmDelete || 'Are you sure you want to delete this question and answer?';
					if (!window.confirm(confirmMsg)){ return; }
				}
				var body = new URLSearchParams();
				body.append('action', 'truebe_gap_action');
				body.append('nonce', nonce);
				body.append('gap_id', gid);
				body.append('gap_act', act);
				body.append('gap_question', q);
				btns.forEach(function(o){ if (o !== btn){ reset(o); } });
				pick(btn);
				fetch(ajax, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() })
					.then(function(r){ return r.json(); })
					.then(function(res){
						if (!res.success){ reset(btn); alert('Could not save. Try again.'); return; }
						adjustBadge(unansweredTab, -1);
						if ('answer' === act && '' !== q){ adjustBadge(answersTab, 1); }
						if ('answer' === act && res.data && res.data.seed_id){
							window.location.href = truebeSeeds.pageUrl + '&sid=' + res.data.seed_id;
							return;
						}
						setTimeout(function(){ removeRow(row); }, 400);
					});
			});
		});
	});
})();

(function(){
	/* Answers tab: autosave, required-field gate, create, approve, publish toggle, confidence tooltip, audit modal */
	if (typeof truebeSeeds === 'undefined') { return; }
	var cfg = truebeSeeds;
	var nonce = cfg.saveNonce, ajax = cfg.ajax;
	var saved = document.querySelector('.truebe-saved');
	var approve = document.getElementById('truebe-approve');
	var t;

	function getField(field){
		return document.querySelector('.truebe-edit[data-field="' + field + '"]');
	}
	function fieldEmpty(field){
		var el = getField(field);
		return !el || el.innerText.trim() === '';
	}
	function markInvalid(field, on){
		var el = getField(field);
		if (el){ el.style.borderColor = on ? '#b32d2e' : ''; el.style.boxShadow = on ? '0 0 0 1px #b32d2e' : ''; }
	}
	function syncRequired(showErrors){
		var qEmpty = fieldEmpty('question');
		var aEmpty = fieldEmpty('answer');
		var missing = qEmpty || aEmpty;
		if (showErrors){
			markInvalid('question', qEmpty);
			markInvalid('answer', aEmpty);
		} else {
			if (!qEmpty){ markInvalid('question', false); }
			if (!aEmpty){ markInvalid('answer', false); }
		}
		if (approve && approve.getAttribute('data-was-ready') !== '1'){
			approve.title = missing ? 'Add a question and answer first.' : '';
		}
		return missing;
	}
	syncRequired(false);

	document.querySelectorAll('.truebe-edit').forEach(function(el){
		var wasReady = approve && approve.getAttribute('data-was-ready') === '1';
		var reloadAfterSave = false;
		el.addEventListener('input', function(){
			syncRequired(false);
			if (approve){
				approve.disabled = false;
				approve.removeAttribute('style');
				approve.innerHTML = cfg.approveLabel;
			}
			if (wasReady){ reloadAfterSave = true; }
			clearTimeout(t);
			t = setTimeout(function(){
				var body = new URLSearchParams();
				body.append('action', 'truebe_seed_save');
				body.append('nonce', nonce);
				body.append('id', el.getAttribute('data-id'));
				body.append('field', el.getAttribute('data-field'));
				body.append('value', el.innerText);
				fetch(ajax, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() }).then(function(){
					if (saved){
						saved.style.display = 'inline-flex';
						clearTimeout(saved._h);
						saved._h = setTimeout(function(){ saved.style.display = 'none'; }, 1500);
					}
					if (reloadAfterSave){
						var sid = el.getAttribute('data-id');
						window.location.href = cfg.pageUrl + '&sid=' + sid;
					}
				});
			}, 600);
		});
	});

	document.querySelectorAll("[data-action='truebe-create']").forEach(function(btn){
		btn.addEventListener('click', function(e){
			e.preventDefault();
			var f = document.createElement('form');
			f.method = 'POST';
			f.action = cfg.adminPost;
			var a = document.createElement('input'); a.type = 'hidden'; a.name = 'action'; a.value = cfg.actionName;
			var b = document.createElement('input'); b.type = 'hidden'; b.name = 'truebe_action'; b.value = 'create';
			var c = document.createElement('input'); c.type = 'hidden'; c.name = '_wpnonce'; c.value = cfg.actionNonce;
			f.appendChild(a); f.appendChild(b); f.appendChild(c);
			document.body.appendChild(f);
			f.submit();
		});
	});

if (approve){
		approve.addEventListener('click', function(e){
			if (e.target.closest('.truebe-approve-caret-toggle')){ return; }
			// Already approved: this click un-approves. No reviewer or field check needed.
			if (approve.getAttribute('data-was-ready') === '1'){
				document.getElementById('truebe-approve-form').submit();
				return;
			}
			if (syncRequired(true)){
				e.preventDefault();
				return;
			}
			var reviewerSelect = document.querySelector("select[name='truebe_reviewer']");
			if (!reviewerSelect || !reviewerSelect.value){
				alert('Select a reviewer');
				e.preventDefault();
				return;
			}
			document.getElementById('truebe-approve-form').submit();
		});
	}

	(function(){
		var caret = document.querySelector('.truebe-approve-caret-toggle');
		var menu  = document.querySelector('.truebe-approve-menu');
		if (!caret || !menu){ return; }
		caret.addEventListener('click', function(e){
			e.preventDefault();
			e.stopPropagation();
			menu.style.display = (menu.style.display === 'block') ? 'none' : 'block';
		});
		document.addEventListener('click', function(e){
			if (!menu.contains(e.target) && !caret.contains(e.target)){ menu.style.display = 'none'; }
		});
	})();

	(function(){
		var tog = document.getElementById('truebe-publish-toggle');
		if (!tog){ return; }
		tog.addEventListener('change', function(){
			var body = new URLSearchParams();
			body.append('action', 'truebe_toggle_published');
			body.append('nonce', tog.getAttribute('data-nonce'));
			body.append('seed_id', tog.getAttribute('data-seed-id'));
			body.append('published', tog.checked ? '1' : '0');
			fetch(ajax, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() })
				.then(function(r){ return r.json(); })
				.then(function(res){ if (!res.success){ tog.checked = !tog.checked; alert('Could not update. Try again.'); } });
		});
	})();

(function(){
		var approveAnyway = document.getElementById('truebe-approve-anyway');
		var form = document.getElementById('truebe-approve-form');
		if (!approveAnyway || !form){ return; }
		approveAnyway.addEventListener('click', function(){
			var reviewerSelect = document.querySelector("select[name='truebe_reviewer']");
			if (!reviewerSelect || !reviewerSelect.value){
				alert('Select a reviewer');
				return;
			}
			var force = document.createElement('input');
			force.type = 'hidden';
			force.name = 'truebe_force';
			force.value = '1';
			form.appendChild(force);
			form.submit();
		});
	})();

	(function(){
		var approveLowConfidence = document.getElementById('truebe-approve-low-confidence');
		var form = document.getElementById('truebe-approve-form');
		if (!approveLowConfidence || !form){ return; }
		approveLowConfidence.addEventListener('click', function(){
			var reviewerSelect = document.querySelector("select[name='truebe_reviewer']");
			if (!reviewerSelect || !reviewerSelect.value){
				alert('Select a reviewer');
				return;
			}
			var force = document.createElement('input');
			force.type = 'hidden';
			force.name = 'truebe_low_confidence_force';
			force.value = '1';
			form.appendChild(force);
			form.submit();
		});
	})();

	(function(){
		var deleteBtn = document.getElementById('truebe-collision-delete');
		if (!deleteBtn || typeof truebeSeeds === 'undefined'){ return; }
		deleteBtn.addEventListener('click', function(){
			var seedId = deleteBtn.getAttribute('data-seed-id');
			if (!seedId || seedId === '0'){ return; }
			var index = deleteBtn.getAttribute('data-index') || '0';
			var msg = truebeSeeds.confirmDelete || 'Are you sure you want to delete this question and answer?';
			if (!window.confirm(msg)){ return; }
			var f = document.createElement('form');
			f.method = 'POST';
			f.action = truebeSeeds.adminPost;
			var a = document.createElement('input'); a.type = 'hidden'; a.name = 'action'; a.value = truebeSeeds.actionName;
			var b = document.createElement('input'); b.type = 'hidden'; b.name = 'truebe_action'; b.value = 'delete';
			var c = document.createElement('input'); c.type = 'hidden'; c.name = 'seed_id'; c.value = seedId;
			var d = document.createElement('input'); d.type = 'hidden'; d.name = '_wpnonce'; d.value = truebeSeeds.actionNonce;
			var e = document.createElement('input'); e.type = 'hidden'; e.name = 'i'; e.value = index;
			f.appendChild(a); f.appendChild(b); f.appendChild(c); f.appendChild(d); f.appendChild(e);
			document.body.appendChild(f);
			f.submit();
		});
	})();

	// Confidence score tooltip: animated bars, colored by state, with reasons.
	(function(){
		var tooltips = document.querySelectorAll('.truebe-confidence-score');
		tooltips.forEach(function(el){
			var tip = document.createElement('div');
			tip.style.cssText = 'position:absolute;left:50%;transform:translateX(-50%);background:#fff;color:#000;padding:14px;border-radius:8px;font-size:12px;width:300px;text-align:left;z-index:100000;pointer-events:none;opacity:0;transition:opacity 0.2s;border:1px solid #e6e6e8;box-shadow:0 6px 20px rgba(0,0,0,0.1);';
			var header = document.createElement('strong');
			header.style.display = 'block';
			header.style.marginBottom = '6px';
			header.textContent = 'The Score';
			var desc = document.createElement('p');
			desc.style.cssText = 'margin:0 0 12px 0;font-size:11px;color:#666;line-height:1.4;';
			desc.textContent = 'This score reflects answer reliability based on source verification, citation coverage, and source detail.';
			tip.appendChild(header);
			tip.appendChild(desc);

			var breakdown = [];
			try { breakdown = JSON.parse(el.getAttribute('data-breakdown') || '[]'); } catch (e) {}

			var fills = [];
			breakdown.forEach(function(item){
				var row = document.createElement('div');
				row.className = 'truebe-score-row';

				var top = document.createElement('div');
				top.className = 'truebe-score-toprow';
				var lbl = document.createElement('span');
				lbl.textContent = item.label;
				var val = document.createElement('span');
				val.style.color = '#8a8a8a';
				val.textContent = item.weight;
				top.appendChild(lbl);
				top.appendChild(val);

				var track = document.createElement('div');
				track.className = 'truebe-score-track';
				var fill = document.createElement('div');
				fill.className = 'truebe-score-fill ' + (item.state || 'red');
				fill.style.width = '0%';
				track.appendChild(fill);
				fills.push({ el: fill, pct: item.pct || 0 });

				var reason = document.createElement('div');
				reason.className = 'truebe-score-reason';
				reason.textContent = item.reason || '';

				row.appendChild(top);
				row.appendChild(track);
				row.appendChild(reason);
				tip.appendChild(row);
			});

			tip.style.maxHeight = '80vh';
			tip.style.overflowY = 'auto';
			el.appendChild(tip);

			el.addEventListener('mouseenter', function(){
				var rect = el.getBoundingClientRect();
				var tipHeight = tip.offsetHeight || 320;
				var opensAbove = rect.top > tipHeight + 20;
				if (opensAbove){
					tip.style.bottom = '100%';
					tip.style.top = 'auto';
					tip.style.marginBottom = '8px';
					tip.style.marginTop = '0';
				} else {
					tip.style.top = '100%';
					tip.style.bottom = 'auto';
					tip.style.marginTop = '8px';
					tip.style.marginBottom = '0';
				}
				tip.style.opacity = '1';
				requestAnimationFrame(function(){
					fills.forEach(function(f){ f.el.style.width = f.pct + '%'; });
				});
			});
			el.addEventListener('mouseleave', function(){
				tip.style.opacity = '0';
				fills.forEach(function(f){ f.el.style.width = '0%'; });
			});
		});
	})();

(function(){
		var hLabel = document.querySelector('.truebe-handoff-label');
		var hUrl   = document.querySelector('.truebe-handoff-url');
		if (!hLabel || !hUrl){ return; }
		var hSaved = document.querySelector('.truebe-handoff-saved');
		var ht;
		function saveHandoff(){
			var sid = hLabel.getAttribute('data-seed-id');
			if (!sid || sid === '0'){ return; }
			var body = new URLSearchParams();
			body.append('action', 'truebe_seed_save');
			body.append('nonce', nonce);
			body.append('id', sid);
			body.append('field', 'handoff');
			body.append('handoff_label', hLabel.value.trim());
			body.append('handoff_url', hUrl.value.trim());
			fetch(ajax, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() })
				.then(function(r){ return r.json(); })
				.then(function(res){
					if (res.success && hSaved){
						hSaved.style.display = 'inline-flex';
						clearTimeout(hSaved._h);
						hSaved._h = setTimeout(function(){ hSaved.style.display = 'none'; }, 1500);
					}
				});
		}
		[hLabel, hUrl].forEach(function(el){
			el.addEventListener('input', function(){
				clearTimeout(ht);
				ht = setTimeout(saveHandoff, 600);
			});
		});
	})();

	(function(){
		var auditNonce = cfg.auditNonce;
		var openBtn = document.getElementById('truebe-audit-open');
		var overlay = document.getElementById('truebe-audit-overlay');
		if (!openBtn || !overlay){ return; }
		var closeBtn = document.getElementById('truebe-audit-close');
		var loading = document.getElementById('truebe-audit-loading');
		var table = document.getElementById('truebe-audit-table');
		var rowsEl = document.getElementById('truebe-audit-rows');
		var countEl = document.getElementById('truebe-audit-count');
		function esc(s){ var d = document.createElement('div'); d.textContent = s == null ? '' : String(s); return d.innerHTML; }
		function load(){
			loading.style.display = 'block';
			loading.textContent = 'Loading\u2026';
			table.style.display = 'none';
			var body = new URLSearchParams();
			body.append('action', 'truebe_audit_fetch');
			body.append('nonce', auditNonce);
			var st = 0;
			fetch(ajax, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() })
				.then(function(r){ st = r.status; return r.text(); })
				.then(function(txt){
					var res;
					try { res = JSON.parse(txt); } catch (e) { loading.textContent = 'HTTP ' + st + ': ' + txt.slice(0, 200); return; }
					if (!res.success){ loading.textContent = 'Failed (' + st + '): ' + (res.data || 'no message'); return; }
					rowsEl.innerHTML = '';
					res.data.rows.forEach(function(row){
						var tr = document.createElement('tr');
						tr.style.borderBottom = '1px solid #f0f0f1';
						tr.innerHTML = "<td style='padding:10px 16px;white-space:nowrap;'>" + esc(row.when) + "</td><td style='padding:10px 16px;'>" + esc(row.seed_id) + "</td><td style='padding:10px 16px;'>" + esc(row.question) + "</td><td style='padding:10px 16px;'>" + esc(row.action) + "</td><td style='padding:10px 16px;'>" + esc(row.approver) + "</td>";
						rowsEl.appendChild(tr);
					});
					loading.style.display = 'none';
					table.style.display = 'table';
					countEl.textContent = res.data.total ? (res.data.total + ' record' + (res.data.total === 1 ? '' : 's')) : 'No records yet.';
				})
				.catch(function(err){ loading.textContent = 'Network error: ' + err.message; });
		}
		openBtn.addEventListener('click', function(){ overlay.style.display = 'flex'; load(); });
		closeBtn.addEventListener('click', function(){ overlay.style.display = 'none'; });
		overlay.addEventListener('click', function(e){ if (e.target === overlay){ overlay.style.display = 'none'; } });
	})();
})();