/**
 * Answyr — settings page behaviour.
 * Cascading model select (per active provider) + per-provider connection test.
 */
(() => {
	var cfg = window.AnswyrSettings || { models: {}, restUrl: '', nonce: '' };

	var providerEl = document.getElementById('answyr-provider');
	var modelEl = document.getElementById('answyr-model');

	function populateModels(provider, preferred) {
		if (!modelEl) {
			return;
		}
		var models = cfg.models[provider] || {};
		modelEl.innerHTML = '';
		Object.keys(models).forEach((id) => {
			var opt = document.createElement('option');
			opt.value = id;
			opt.textContent = models[id];
			if (id === preferred) {
				opt.selected = true;
			}
			modelEl.appendChild(opt);
		});
	}

	if (providerEl && modelEl) {
		populateModels(providerEl.value, modelEl.getAttribute('data-active-model'));
		providerEl.addEventListener('change', () => {
			populateModels(providerEl.value, null);
		});
	}

	// Tracks whether an API key field has been edited but not yet saved, so a green
	// "Test" result doesn't fool the user into leaving without clicking Save Changes.
	var keyDirty = false;
	var keyInputs = Array.prototype.slice.call(document.querySelectorAll('[id^="answyr-key-"]'));
	keyInputs.forEach((input) => {
		input.addEventListener('input', () => {
			if (input.value !== '') {
				keyDirty = true;
			}
		});
	});

	// Warn before navigating away with an unsaved (but perhaps just-tested) key.
	window.addEventListener('beforeunload', (e) => {
		if (keyDirty) {
			e.preventDefault();
			e.returnValue = '';
		}
	});

	// Clear the guard once the settings form is actually submitted (Save Changes).
	var settingsForm = document.querySelector('.answyr-settings form, form.answyr-settings-form');
	if (settingsForm) {
		settingsForm.addEventListener('submit', () => {
			keyDirty = false;
		});
	}

	// Test-connection buttons.
	document.querySelectorAll('.answyr-test-connection').forEach((btn) => {
		btn.addEventListener('click', () => {
			var provider = btn.getAttribute('data-provider');
			var keyInput = document.getElementById(`answyr-key-${provider}`);
			var result = document.querySelector(`.answyr-test-result[data-provider="${provider}"]`);
			var original = btn.textContent;

			btn.disabled = true;
			btn.textContent = 'Testing…';
			if (result) {
				result.textContent = '';
				result.classList.remove('is-ok', 'is-error');
			}

			fetch(cfg.restUrl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce },
				body: JSON.stringify({
					provider: provider,
					api_key: keyInput ? keyInput.value : '',
				}),
			})
				.then((r) => r.json())
				.then((data) => {
					if (result) {
						if (data.ok) {
							// A green test on a freshly typed key hasn't stored anything yet —
							// nudge the user to Save so they don't navigate away and lose it.
							result.textContent =
								keyInput && keyInput.value !== ''
									? `✓ ${data.message || 'OK'} — click "Save Changes" to store this key.`
									: `✓ ${data.message || 'OK'}`;
						} else {
							result.textContent = `✗ ${data.error || data.message || 'Failed'}`;
						}
						result.classList.add(data.ok ? 'is-ok' : 'is-error');
					}
				})
				.catch((e) => {
					if (result) {
						result.textContent = `✗ ${e.message}`;
						result.classList.add('is-error');
					}
				})
				.finally(() => {
					btn.disabled = false;
					btn.textContent = original;
				});
		});
	});
})();

/**
 * Section tabs — toggle the .answyr-card[data-answyr-tab] panels client-side so the long
 * settings form reads as tabbed sections. No-JS keeps every card visible.
 */
(() => {
	var nav = document.querySelector('.answyr-settings-tabs');
	if (!nav) {
		return;
	}
	var tabs = Array.prototype.slice.call(nav.querySelectorAll('.nav-tab'));
	var cards = Array.prototype.slice.call(
		document.querySelectorAll('.answyr-card[data-answyr-tab]'),
	);
	var saveRow = document.querySelector('.answyr-settings-save');
	var ids = tabs.map((t) => t.getAttribute('data-answyr-tab'));
	var STORAGE_KEY = 'ss_settings_tab';

	function activate(id) {
		tabs.forEach((t) => {
			t.classList.toggle('nav-tab-active', t.getAttribute('data-answyr-tab') === id);
		});
		cards.forEach((c) => {
			c.hidden = c.getAttribute('data-answyr-tab') !== id;
		});
		// The main Save button drives the settings form; the Pages tab has its own.
		if (saveRow) {
			saveRow.hidden = id === 'pages';
		}
		try {
			window.localStorage.setItem(STORAGE_KEY, id);
		} catch (_e) {
			// storage may be unavailable — tabs still work for the session
		}
	}

	tabs.forEach((t) => {
		t.addEventListener('click', (e) => {
			e.preventDefault();
			activate(t.getAttribute('data-answyr-tab'));
		});
	});

	var hash = window.location.hash.replace('#answyr-', '');
	var stored = '';
	try {
		stored = window.localStorage.getItem(STORAGE_KEY) || '';
	} catch (_e) {
		stored = '';
	}
	var initial = ids.indexOf(hash) !== -1 ? hash : ids.indexOf(stored) !== -1 ? stored : ids[0];
	activate(initial);
})();
