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

	var testBtn = document.getElementById('lens-test-connection');
	var keyInput = document.getElementById('openai_api_key');
	if (!testBtn) { return; }

	testBtn.addEventListener('click', function () {
		var key = keyInput ? keyInput.value.trim() : '';
		// If no key entered, test the already-stored key.
		var payload = key ? { provider: 'openai', key: key } : { provider: 'openai' };
		lens.busy(testBtn, true);
		lens.api('test_provider', payload).then(function (data) {
			lens.toast(data.message || 'Connection successful.', 'ok');
		}).catch(function (e) {
			lens.toast(e.message, 'bad');
		}).finally(function () {
			lens.busy(testBtn, false);
		});
	});

	// Live key-format validation (sk-... is OpenAI convention)
	if (keyInput) {
		keyInput.addEventListener('input', function () {
			var v = keyInput.value.trim();
			if (!v) { keyInput.style.borderColor = ''; return; }
			keyInput.style.borderColor = v.startsWith('sk-') ? '#117a3a' : '#d4a017';
		});
	}
})();
