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

	// Step 2 — test/save key
	var testBtn = document.getElementById('lens-test-key-btn');
	var saveBtn = document.getElementById('lens-save-key-next');
	var keyInput = document.getElementById('welcome-openai-key');

	if (testBtn && keyInput) {
		testBtn.addEventListener('click', function () {
			var key = keyInput.value.trim();
			if (!key) { lens.toast('Enter a key first.', 'warn'); return; }
			lens.busy(testBtn, true);
			lens.api('test_provider', { provider: 'openai', key: key })
				.then(function () { lens.toast('Key works.', 'ok'); })
				.catch(function (e) { lens.toast(e.message, 'bad'); })
				.finally(function () { lens.busy(testBtn, false); });
		});
	}

	if (saveBtn) {
		saveBtn.addEventListener('click', function () {
			var key = keyInput ? keyInput.value.trim() : '';
			if (!key) {
				window.location.href = saveBtn.dataset.next || (window.location.href.replace(/step=\d+/, 'step=3'));
				return;
			}
			lens.busy(saveBtn, true);
			// Save by POSTing to the normal settings handler.
			var form = document.getElementById('lens-welcome-key-form');
			form.submit();
			// After submit, we'll redirect — but to be helpful pre-redirect:
		});
	}

	// Step 3 — save modules
	var modulesBtn = document.getElementById('lens-save-modules-next');
	if (modulesBtn) {
		modulesBtn.addEventListener('click', function () {
			lens.busy(modulesBtn, true);
			document.getElementById('lens-welcome-modules').submit();
		});
	}
})();
