(function(){
	/* Connection tab: provider tiles, save button, key help */
	document.querySelectorAll('.truebe-tile').forEach(function(tile){
		tile.addEventListener('click', function(){
			var input = tile.querySelector('input');
			if (!input) { return; }
			input.checked = true;
			document.querySelectorAll('.truebe-tile').forEach(function(t){ t.classList.remove('is-selected'); });
			tile.classList.add('is-selected');
		});
	});
	var form = document.querySelector('.truebe-settings form');
	var btn  = form ? form.querySelector('.truebe-save') : null;
	if (form && btn && form.id !== 'truebe-upload-form') {
		form.addEventListener('submit', function(e){
			if (e.defaultPrevented){ return; }
			btn.textContent = 'Checking...'; btn.disabled = true; btn.style.opacity = '0.7';
		});
	}
	function truebeSyncProviderHelp(){
		var openai = document.querySelector('.truebe-openai input') && document.querySelector('.truebe-openai input').checked;
		document.querySelectorAll('.truebe-keyhelp [data-claude]').forEach(function(el){ el.style.display = openai ? 'none' : ''; });
		document.querySelectorAll('.truebe-keyhelp [data-openai]').forEach(function(el){ el.style.display = openai ? '' : 'none'; });
	}
	document.querySelectorAll('.truebe-tile').forEach(function(t){ t.addEventListener('click', truebeSyncProviderHelp); });
	function truebeSyncKeyhelp(){
		var claude = document.querySelector('.truebe-claude input') && document.querySelector('.truebe-claude input').checked;
		var openai = document.querySelector('.truebe-openai input') && document.querySelector('.truebe-openai input').checked;
		var keyhelp = document.getElementById('truebe-keyhelp');
		if(keyhelp){ keyhelp.style.display = (claude||openai) ? '' : 'none'; }
	}
	document.querySelectorAll('.truebe-tile').forEach(function(t){ t.addEventListener('click', truebeSyncKeyhelp); });
	truebeSyncProviderHelp();
	truebeSyncKeyhelp();
})();

(function(){
	/* Connection tab: replace key reveal, provider-switch warning, dismissal,
	 * and save guard: a switched provider with an empty key field must never
	 * save, because the old provider's key would be silently kept and every
	 * chat call would fail. */
	var replaceBtn = document.getElementById('truebe-replace-key');
	var replaceBox = document.getElementById('truebe-key-replace');
	var switchNote = document.getElementById('truebe-key-switch-note');
	if (!replaceBtn || !replaceBox) { return; }
	var keyInput   = replaceBox.querySelector('input');
	var initial    = (function(){
		var sel = document.querySelector('.truebe-tile input:checked');
		return sel ? sel.value : '';
	})();

	function openBox(withNote){
		replaceBox.style.display = 'block';
		if (switchNote){ switchNote.style.display = withNote ? 'block' : 'none'; }
		if (keyInput){ keyInput.focus(); }
	}
	function closeBox(){
		replaceBox.style.display = 'none';
		if (switchNote){ switchNote.style.display = 'none'; }
		if (keyInput){ keyInput.value = ''; }
	}
	function providerSwitched(){
		var sel = document.querySelector('.truebe-tile input:checked');
		return sel ? sel.value !== initial : false;
	}

	replaceBtn.addEventListener('click', function(e){
		e.stopPropagation();
		openBox(providerSwitched());
	});

	document.querySelectorAll('.truebe-tile').forEach(function(tile){
		tile.addEventListener('click', function(e){
			e.stopPropagation();
			if (providerSwitched()){
				openBox(true);
			} else if (keyInput && '' === keyInput.value.trim()){
				closeBox();
			} else if (switchNote){
				switchNote.style.display = 'none';
			}
		});
	});

	/* Save guard. Registered before the generic submit handler runs its
	 * button-disable via the defaultPrevented check in that handler. */
	var form = replaceBox.closest('form') || document.querySelector('.truebe-settings form');
	if (form && form.id !== 'truebe-upload-form'){
		form.addEventListener('submit', function(e){
			if (!providerSwitched()){ return; }
			if (keyInput && '' !== keyInput.value.trim()){ return; }
			e.preventDefault();
			openBox(true);
			var err = document.getElementById('truebe-key-required-note');
			if (!err){
				err = document.createElement('p');
				err.id = 'truebe-key-required-note';
				err.style.cssText = 'color:#b32d2e;font-size:13px;margin:6px 0 0;';
				err.textContent = 'Paste an API key for the new provider before saving.';
				replaceBox.appendChild(err);
			}
			err.style.display = 'block';
			if (keyInput){
				keyInput.focus();
				keyInput.addEventListener('input', function hide(){
					if ('' !== keyInput.value.trim()){
						err.style.display = 'none';
						keyInput.removeEventListener('input', hide);
					}
				});
			}
		}, true);
	}

	/* Dismiss when clicking anywhere outside the reveal, but only if nothing
	 * was typed, so a stray click never discards a pasted key. Never dismiss
	 * while the provider is switched away from the saved key's provider. */
	document.addEventListener('click', function(e){
		if (replaceBox.style.display === 'none'){ return; }
		if (replaceBox.contains(e.target)){ return; }
		if (providerSwitched()){ return; }
		if (keyInput && '' !== keyInput.value.trim()){ return; }
		closeBox();
	});
	document.addEventListener('keydown', function(e){
		if (e.key !== 'Escape'){ return; }
		if (replaceBox.style.display === 'none'){ return; }
		if (providerSwitched()){ return; }
		closeBox();
	});
})();

(function(){
	/* Connection tab: API key setup guide modals (Claude + OpenAI) */
	function wireModal(modalId, openId){
		var modal = document.getElementById(modalId);
		var open  = document.getElementById(openId);
		if (!modal || !open) { return; }
		var steps = modal.querySelectorAll('.truebe-step');
		var cur = 0;
		function show(n){
			steps.forEach(function(s,i){ s.hidden = (i !== n); });
			cur = n;
			var a = steps[n];
			var p = a.querySelector('.truebe-prev');
			var nx = a.querySelector('.truebe-next');
			if (p){ p.disabled = (n === 0); }
			if (nx){ nx.textContent = (n === steps.length - 1) ? 'Done' : 'Next'; }
		}
		function openModal(){ modal.hidden = false; show(0); }
		function closeModal(){ modal.hidden = true; }
		open.addEventListener('click', openModal);
		modal.querySelectorAll('.truebe-next').forEach(function(b){ b.addEventListener('click', function(){ if (cur < steps.length - 1){ show(cur + 1); } else { closeModal(); } }); });
		modal.querySelectorAll('.truebe-prev').forEach(function(b){ b.addEventListener('click', function(){ if (cur > 0){ show(cur - 1); } }); });
		modal.querySelectorAll('[data-close]').forEach(function(el){ el.addEventListener('click', closeModal); });
		document.addEventListener('keydown', function(e){ if (!modal.hidden && e.key === 'Escape'){ closeModal(); } });
	}
	wireModal('truebe-guide', 'truebe-open-guide');
	wireModal('truebe-guide-openai', 'truebe-open-guide-openai');
})();

(function(){
	/* Appearance tab: live preview */
	var f = document.querySelector('.truebe-ap');
	if (!f){ return; }
	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'; }
	var get = function(n){ return f.querySelector('[name="' + n + '"]'); };
	var header = get('truebe_chat_header'), greet = get('truebe_chat_greeting');
	var cA = get('truebe_chat_accent'), cB = get('truebe_chat_bot_color'), cF = get('truebe_chat_fallback_color');
	var pv = document.getElementById('tap-pv');
	var pHead = document.getElementById('tap-head'), pGreet = document.getElementById('tap-greet'), pUser = document.getElementById('tap-user');
	var pSend = document.getElementById('tap-send'), pMic = document.getElementById('tap-mic'), pFb = document.getElementById('tap-fb');
	var pI1 = document.getElementById('tap-i1'), pI2 = document.getElementById('tap-i2');
	var hA = document.getElementById('tap-hA'), hB = document.getElementById('tap-hB'), hF = document.getElementById('tap-hF');
	var sitePH = pHead.getAttribute('data-ph') || 'Your business';
	function applyText(){ pHead.textContent = header.value || sitePH; pGreet.textContent = greet.value; }
	function applyAccent(){ var a = cA.value; hA.value = a.toUpperCase(); pUser.style.background = mix(a,'#ffffff',.86); pUser.style.color = mix(a,'#000000',.15); pSend.style.color = a; }
	function applyBot(){ var b = cB.value; hB.value = b.toUpperCase(); pGreet.style.background = b; pGreet.style.color = ink(b); }
	function applyFb(){ var fc = cF.value; hF.value = fc.toUpperCase(); var tile = mix(fc,'#000000',.07), txt = ink(fc); pFb.style.background = fc; pFb.style.color = txt; [pI1,pI2].forEach(function(el){ el.style.background = tile; el.style.color = txt; }); }
	header.addEventListener('input', applyText); greet.addEventListener('input', applyText);
	cA.addEventListener('input', applyAccent); cB.addEventListener('input', applyBot); cF.addEventListener('input', applyFb);

	function bindHex(field, picker, apply){
		field.addEventListener('input', function(){
			var v = field.value.trim();
			if (v && v.charAt(0) !== '#'){ v = '#' + v; }
			if (/^#[0-9a-fA-F]{6}$/.test(v)){ picker.value = v.toLowerCase(); apply(); }
		});
		field.addEventListener('blur', function(){ field.value = picker.value.toUpperCase(); });
	}
	bindHex(hA, cA, applyAccent); bindHex(hB, cB, applyBot); bindHex(hF, cF, applyFb);
		var wHidden = get('truebe_chat_width');
	var pvCol = document.querySelector('.truebe-ap-pvcol');
	f.querySelectorAll('.truebe-ap-preset').forEach(function(p){ p.addEventListener('click', function(){ f.querySelectorAll('.truebe-ap-preset').forEach(function(x){ x.classList.remove('is-active'); }); p.classList.add('is-active'); wHidden.value = p.getAttribute('data-val'); var w = p.getAttribute('data-w') + 'px'; pv.style.maxWidth = w; if (pvCol){ pvCol.style.maxWidth = w; } }); });
	var audio = f.querySelector('input[name="truebe_chat_audio"][type="checkbox"]');
	audio.addEventListener('change', function(){ pMic.style.display = audio.checked ? 'flex' : 'none'; });
	var sugg = f.querySelector('input[name="truebe_chat_suggestions"][type="checkbox"]');
	sugg.addEventListener('change', function(){ pFb.style.display = sugg.checked ? 'block' : 'none'; });
	var fbMsg = get('truebe_fallback_message');
	var pFbTitle = document.getElementById('tap-fbtitle');
	var fbTitleDefault = pFbTitle ? (pFbTitle.getAttribute('data-default') || pFbTitle.textContent) : '';
	function applyFbMsg(){ if (pFbTitle){ pFbTitle.textContent = fbMsg.value.trim() || fbTitleDefault; } }
	if (fbMsg){ fbMsg.addEventListener('input', applyFbMsg); }
	applyAccent(); applyBot(); applyFb(); applyFbMsg();
})();

(function(){
	/* Appearance tab: copy shortcode button, with icon-swap on success */
	var btn = document.getElementById('truebe-shortcode-copy');
	var input = document.getElementById('truebe-shortcode');
	if (!btn || !input) { return; }
	var originalHTML = btn.innerHTML;
	var checkHTML = '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>';

	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);
		});
	}

	btn.addEventListener('click', function(){
		var code = btn.getAttribute('data-code') || input.value;
		copyText(code).then(function(){
			btn.innerHTML = checkHTML;
			clearTimeout(btn._h);
			btn._h = setTimeout(function(){ btn.innerHTML = originalHTML; }, 1500);
		});
	});
})();

(function(){
	/* Support tab: send message to the Truebe feedback endpoint via admin-ajax. */
	if (typeof truebeSupport === 'undefined') { return; }
	var btn = document.getElementById('truebe-support-submit');
	var msgEl = document.getElementById('truebe-support-message');
	var emailEl = document.getElementById('truebe-support-email');
	var sentEl = document.getElementById('truebe-support-sent');
	if (!btn || !msgEl) { return; }
	btn.addEventListener('click', function(){
		var message = msgEl.value.trim();
		if (!message) { msgEl.focus(); return; }
		btn.disabled = true;
		btn.textContent = 'Sending...';
		var body = new URLSearchParams();
		body.append('action', 'truebe_support_submit');
		body.append('nonce', truebeSupport.nonce);
		body.append('message', message);
		body.append('email', emailEl ? emailEl.value.trim() : '');
		fetch(truebeSupport.ajax, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body.toString() })
			.then(function(r){ return r.json(); })
			.then(function(res){
				btn.disabled = false;
				btn.textContent = 'Send message';
				if (res && res.success) {
					msgEl.value = '';
					if (emailEl) { emailEl.value = ''; }
					if (sentEl) {
						sentEl.style.display = 'inline-flex';
						clearTimeout(sentEl._h);
						sentEl._h = setTimeout(function(){ sentEl.style.display = 'none'; }, 3000);
					}
				} else {
					alert('Could not send. Please try again.');
				}
			})
			.catch(function(){
				btn.disabled = false;
				btn.textContent = 'Send message';
				alert('Could not send. Please try again.');
			});
	});
})();