/**
 * Search Console Connector — settings page.
 *
 * Connect / test / sync / disconnect via admin-ajax. Hardened against
 * non-JSON (timeout/HTML) responses like the rest of the plugin.
 */
(function () {
	'use strict';

	var CFG = window.PlatformHelmGsc || {};

	function ajax(action, data) {
		var body = new FormData();
		body.append('action', action);
		body.append('nonce', CFG.nonce);
		Object.keys(data || {}).forEach(function (k) {
			body.append(k, data[k]);
		});
		return fetch(CFG.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body })
			.then(function (r) { return r.text(); })
			.then(function (text) {
				var j;
				try { j = JSON.parse(text); }
				catch (e) { throw new Error('Unexpected server response (possible timeout). Try again.'); }
				if (!j || j.success !== true) {
					throw new Error((j && j.data && j.data.message) || 'Request failed.');
				}
				return j.data;
			});
	}

	function setMsg(id, text, isError) {
		var el = document.getElementById(id);
		if (!el) return;
		el.textContent = (isError ? '⚠ ' : '') + text;
		el.className = 'ph-gsc-msg' + (isError ? ' is-error' : ' is-ok');
	}

	function fillProperties(select, sites, current) {
		if (!select) return;
		select.innerHTML = '';
		if (!sites || !sites.length) {
			var opt = document.createElement('option');
			opt.value = '';
			opt.textContent = 'No properties found for this service account';
			select.appendChild(opt);
			return;
		}
		sites.forEach(function (s) {
			var opt = document.createElement('option');
			opt.value = s.siteUrl;
			opt.textContent = s.siteUrl + (s.permissionLevel ? '  (' + s.permissionLevel + ')' : '');
			if (s.siteUrl === current) opt.selected = true;
			select.appendChild(opt);
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		var oauthBtn = document.getElementById('ph-gsc-oauth-connect');
		if (oauthBtn) {
			oauthBtn.addEventListener('click', function () {
				var id = (document.getElementById('ph-gsc-client-id') || {}).value || '';
				var secret = (document.getElementById('ph-gsc-client-secret') || {}).value || '';
				if (!id.trim() || !secret.trim()) { setMsg('ph-gsc-oauth-msg', 'Enter both the Client ID and Secret.', true); return; }
				oauthBtn.disabled = true;
				setMsg('ph-gsc-oauth-msg', 'Redirecting to Google…', false);
				ajax('platform_helm_gsc_save_oauth', { client_id: id, client_secret: secret })
					.then(function (d) {
						if (d && d.auth_url) { window.location.href = d.auth_url; }
						else { setMsg('ph-gsc-oauth-msg', 'Could not build the Google sign-in URL.', true); oauthBtn.disabled = false; }
					})
					.catch(function (err) {
						setMsg('ph-gsc-oauth-msg', err.message, true);
						oauthBtn.disabled = false;
					});
			});
		}

		var connectBtn = document.getElementById('ph-gsc-connect');
		if (connectBtn) {
			connectBtn.addEventListener('click', function () {
				var json = (document.getElementById('ph-gsc-json') || {}).value || '';
				if (!json.trim()) { setMsg('ph-gsc-connect-msg', 'Paste the key file first.', true); return; }
				connectBtn.disabled = true;
				setMsg('ph-gsc-connect-msg', 'Connecting…', false);
				ajax('platform_helm_gsc_save', { credentials: json, property: '' })
					.then(function (d) {
						setMsg('ph-gsc-connect-msg', d.message || 'Connected.', false);
						setTimeout(function () { window.location.reload(); }, 900);
					})
					.catch(function (err) {
						setMsg('ph-gsc-connect-msg', err.message, true);
						connectBtn.disabled = false;
					});
			});
		}

		var refreshBtn = document.getElementById('ph-gsc-refresh');
		var propSelect = document.getElementById('ph-gsc-property');
		if (refreshBtn && propSelect) {
			refreshBtn.addEventListener('click', function () {
				refreshBtn.disabled = true;
				ajax('platform_helm_gsc_test', {})
					.then(function (d) {
						fillProperties(propSelect, d.sites, d.property || propSelect.value);
						refreshBtn.disabled = false;
					})
					.catch(function (err) {
						setMsg('ph-gsc-sync-msg', err.message, true);
						refreshBtn.disabled = false;
					});
			});

			propSelect.addEventListener('change', function () {
				if (!propSelect.value) return;
				ajax('platform_helm_gsc_test', { property: propSelect.value })
					.then(function () { setMsg('ph-gsc-sync-msg', 'Property saved.', false); })
					.catch(function (err) { setMsg('ph-gsc-sync-msg', err.message, true); });
			});
		}

		var rangeBtn = document.getElementById('ph-gsc-save-range');
		if (rangeBtn) {
			rangeBtn.addEventListener('click', function () {
				var input = document.getElementById('ph-gsc-range');
				var days = input ? parseInt(input.value, 10) : 90;
				if (isNaN(days)) days = 90;
				rangeBtn.disabled = true;
				ajax('platform_helm_gsc_save_range', { days: days })
					.then(function (d) { setMsg('ph-gsc-sync-msg', d.message || 'Saved.', false); rangeBtn.disabled = false; })
					.catch(function (err) { setMsg('ph-gsc-sync-msg', err.message, true); rangeBtn.disabled = false; });
			});
		}

		var syncBtn = document.getElementById('ph-gsc-sync');
		if (syncBtn) {
			syncBtn.addEventListener('click', function () {
				syncBtn.disabled = true;
				setMsg('ph-gsc-sync-msg', 'Syncing — this can take a moment…', false);
				ajax('platform_helm_gsc_sync', {})
					.then(function (d) {
						setMsg('ph-gsc-sync-msg', d.message || 'Done.', false);
						setTimeout(function () { window.location.reload(); }, 1200);
					})
					.catch(function (err) {
						setMsg('ph-gsc-sync-msg', err.message, true);
						syncBtn.disabled = false;
					});
			});
		}

		var disconnectBtn = document.getElementById('ph-gsc-disconnect');
		if (disconnectBtn) {
			disconnectBtn.addEventListener('click', function () {
				if (!confirm('Disconnect the Google service account? Cached metrics are kept.')) return;
				disconnectBtn.disabled = true;
				ajax('platform_helm_gsc_disconnect', {})
					.then(function () { window.location.reload(); })
					.catch(function (err) { setMsg('ph-gsc-sync-msg', err.message, true); disconnectBtn.disabled = false; });
			});
		}
	});
})();
