(function ($) {
	'use strict';

	var cfg = window.sftcyWordaiSearchConsole || {};
	var state = null;
	var pendingCallbackNotice = null;

	function esc(value) {
		return $('<div>').text(value == null ? '' : String(value)).html();
	}

	function request(action, data) {
		return $.post(cfg.ajaxUrl, $.extend({
			action: 'sftcy_wordai_search_console_' + action,
			nonce: cfg.nonce
		}, data || {}));
	}

	function notice(message, error) {
		var element = $('#wordai-sc-notice');
		if (!message) {
			element.prop('hidden', true).removeClass('is-error').text('');
			return;
		}
		element.prop('hidden', false).toggleClass('is-error', !!error).text(message);
	}

	function errorMessage(xhr) {
		var message = xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message
			? xhr.responseJSON.data.message
			: 'The request could not be completed.';
		if (/(\broute\b|\/api\/|api\/v\d+|services\/search-console|endpoint)/i.test(String(message))) {
			return 'SOFTCOY hosted services are temporarily unavailable. Please try again later or contact support if this continues.';
		}
		return message;
	}

	function providerLabel(provider) {
		return (cfg.providerLabels && cfg.providerLabels[provider]) ? cfg.providerLabels[provider] : provider;
	}

	function providerIcon(provider) {
		var icons = cfg.providerIcons || {};
		if (icons[provider]) {
			return '<span class="sc-wordai-provider-modal-icon"><img src="' + esc(icons[provider]) + '" alt="" aria-hidden="true"></span>';
		}
		if (provider === 'anthropic') {
			return '<span class="sc-wordai-provider-modal-icon"><i class="fa-solid fa-brain" aria-hidden="true"></i></span>';
		}
		if (provider === 'xai') {
			return '<span class="sc-wordai-provider-modal-icon"><i class="fa-solid fa-bolt" aria-hidden="true"></i></span>';
		}
		return '<span class="sc-wordai-provider-modal-icon"><span aria-hidden="true">AI</span></span>';
	}

	function showProviderSwitchDialog(provider, onConfirm, onCancel) {
		var label = providerLabel(provider);
		var html = '<div class="sc-wordai-provider-switch-dialog-body">' +
			providerIcon(provider) +
			'<div><strong>' + esc(label) + ' settings will load now.</strong>' +
			'<p>Click OK to reload this page with the selected provider settings. Close this window to keep the previous provider.</p></div>' +
			'</div>';

		if (typeof window.scWordaiShowInfoDialog === 'function') {
			window.scWordaiShowInfoDialog(label + ' selected', html, onConfirm, onCancel);
			return;
		}

		notice(label + ' settings will load now.');
		window.setTimeout(function () {
			if (typeof onConfirm === 'function') {
				onConfirm();
			}
		}, 900);
	}

	function showLoading(show) {
		$('#wordai-sc-loading').toggle(!!show);
	}

	function empty(message) {
		return '<div class="wordai-sc-empty">' + esc(message) + '</div>';
	}

	function metric(label, value) {
		return '<div class="wordai-sc-metric"><span>' + esc(label) + '</span><strong>' + esc(value) + '</strong></div>';
	}

	function render(data) {
		state = data || {};
		var capabilities = state.capabilities || {};
		var searchConsole = capabilities.search_console || {};
		var connection = state.connection || null;
		var properties = connection && connection.properties ? connection.properties : [];
		var connected = connection && connection.status === 'connected';
		var hasProAccess = !!cfg.isPro || capabilities.tier === 'pro';
		var hasSelectedProperty = properties.some(function (property) {
			return !!property.selected;
		});

		$('#wordai-sc-property-limit').text(
			'Up to ' + (searchConsole.max_properties || 1) + ' selected ' +
			((searchConsole.max_properties || 1) === 1 ? 'property' : 'properties') + '.'
		);
		$('#wordai-sc-account').text(connection && connection.account_email ? connection.account_email : 'Not connected');
		$('#wordai-sc-connection-state').text(
			connection ? connection.status.charAt(0).toUpperCase() + connection.status.slice(1) : 'Disconnected'
		);
		$('#wordai-sc-connect').prop('hidden', !!connected);
		$('.wordai-sc-refresh-properties').prop('hidden', !connected);
		$('#wordai-sc-disconnect').prop('hidden', !connected);
		$('#wordai-sc-sync').prop('disabled', !connected || !hasSelectedProperty);

		renderProperties(properties, connected);
		renderDashboard(state.dashboard);
		renderOpportunities(state.opportunities);

		if (!hasProAccess) {
			$('[data-panel="opportunities"] .wordai-sc-upgrade').remove();
			$('[data-panel="opportunities"]').append(
				'<div class="wordai-sc-upgrade">Free includes up to 5 content-decay and 5 competing-page findings. ' +
				'<a href="' + esc(cfg.upgradeUrl) + '" target="_blank" rel="noopener">Upgrade to WordAI Pro</a> ' +
				'for expanded reporting.</div>'
			);
		}

		if (!connected) {
			notice(
				connection && connection.last_error_message
					? connection.last_error_message
					: 'Connect Google Search Console to load performance reports.',
				connection && connection.status === 'error'
			);
		} else if (pendingCallbackNotice) {
			notice(pendingCallbackNotice.message, !!pendingCallbackNotice.error);
			pendingCallbackNotice = null;
		} else {
			notice('');
		}
	}

	function renderProperties(properties, connected) {
		var box = $('#wordai-sc-properties');
		if (!properties.length) {
			if (connected) {
				box.html(
					'<div class="wordai-sc-empty wordai-sc-empty-panel">' +
						'<strong>No Search Console property found for this Google account.</strong>' +
						'<p>Google did not return any verified website property for the connected Gmail account. Add or verify a property in Google Search Console, or ask the property owner to grant this Gmail access. Reports will appear here after a property is available and selected.</p>' +
						'<div class="wordai-sc-empty-actions">' +
							'<a class="button button-secondary wordai-sc-icon-button" href="https://search.google.com/search-console" target="_blank" rel="noopener"><span class="dashicons dashicons-external" aria-hidden="true"></span>Open Search Console</a>' +
							'<button type="button" class="button button-primary wordai-sc-icon-button wordai-sc-refresh-properties"><span class="dashicons dashicons-update" aria-hidden="true"></span>Refresh properties</button>' +
						'</div>' +
					'</div>'
				);
				return;
			}
			box.html(empty('Connect Google Search Console to load your verified properties.'));
			return;
		}

		box.html(properties.map(function (property) {
			var details = '<div><strong>' + esc(property.site_url) + '</strong><small>' +
				esc(property.permission_level || 'Access available') +
				(property.last_synced_at ? ' · Last synced ' + esc(new Date(property.last_synced_at).toLocaleString()) : '') +
				'</small></div>';
			var action = property.selected
				? '<div class="wordai-sc-property-actions"><span class="wordai-sc-state">Selected</span>' +
					'<button type="button" class="button wordai-sc-toggle-property" data-id="' + Number(property.id) +
					'" data-selected="0">Deselect</button></div>'
				: '<button type="button" class="button wordai-sc-toggle-property" data-id="' + Number(property.id) +
					'" data-selected="1">Select</button>';

			return '<div class="wordai-sc-property ' + (property.selected ? 'is-selected' : '') + '">' + details + action + '</div>';
		}).join(''));
	}

	function renderDashboard(dashboard) {
		if (!dashboard) {
			$('#wordai-sc-metrics').html(
				metric('Clicks', '—') + metric('Impressions', '—') + metric('Average position', '—')
			);
			$('#wordai-sc-period').text('Select a property and synchronize data.');
			$('#wordai-sc-pages').html('<tr><td colspan="4">No synchronized data yet.</td></tr>');
			return;
		}

		var totals = dashboard.totals || {};
		$('#wordai-sc-metrics').html(
			metric('Clicks', Number(totals.clicks || 0).toLocaleString()) +
			metric('Impressions', Number(totals.impressions || 0).toLocaleString()) +
			metric('Average position', Number(totals.average_position || 0).toFixed(2))
		);
		$('#wordai-sc-period').text(dashboard.period ? dashboard.period.start + ' to ' + dashboard.period.end : '');

		var pages = dashboard.top_pages || [];
		$('#wordai-sc-pages').html(pages.length ? pages.map(function (page) {
			return '<tr><td>' + esc(page.page || '') + '</td><td>' + esc(page.clicks) + '</td><td>' +
				esc(page.impressions) + '</td><td>' + esc(page.position) + '</td></tr>';
		}).join('') : '<tr><td colspan="4">No page metrics were returned for this period.</td></tr>');
	}

	function renderOpportunities(data) {
		var decay = data && data.content_decay ? data.content_decay : [];
		var cannibalization = data && data.cannibalization ? data.cannibalization : [];

		$('#wordai-sc-decay').html(decay.length ? decay.map(function (item) {
			return decayCard(item);
		}).join('') : empty('No content-decay findings yet.'));

		$('#wordai-sc-cannibalization').html(cannibalization.length ? cannibalization.map(function (item) {
			return cannibalizationCard(item);
		}).join('') : empty('No competing-page findings yet.'));
	}

	function formatNumber(value) {
		value = Number(value || 0);
		return value.toLocaleString(undefined, { maximumFractionDigits: value % 1 === 0 ? 0 : 2 });
	}

	function metricPill(label, value) {
		return '<span class="wordai-sc-mini-metric"><b>' + esc(value) + '</b>' + esc(label) + '</span>';
	}

	function opportunityActions(localPost, pageUrl) {
		if (!localPost) {
			return '<div class="wordai-sc-opportunity-actions">' +
				'<a class="button button-secondary wordai-sc-icon-button" href="' + esc(pageUrl || '#') + '" target="_blank" rel="noopener">' +
					'<span class="dashicons dashicons-external" aria-hidden="true"></span>Open page</a>' +
				'<span class="wordai-sc-local-note">No matching local post was found for this URL.</span>' +
			'</div>';
		}

		return '<div class="wordai-sc-opportunity-actions">' +
			'<a class="button button-primary wordai-sc-icon-button" href="' + esc(localPost.seo_scan_url || cfg.seoScanUrl || '#') + '">' +
				'<span class="dashicons dashicons-search" aria-hidden="true"></span>Open in SEO Scan</a>' +
			'<a class="button button-secondary wordai-sc-icon-button" href="' + esc(localPost.edit_url || '#') + '">' +
				'<span class="dashicons dashicons-edit" aria-hidden="true"></span>Edit content</a>' +
		'</div>';
	}

	function decayCard(item) {
		var localPost = item.local_post || null;
		var title = localPost && localPost.title ? localPost.title : item.page;
		var priority = item.priority || 'medium';
		var pageUrl = item.page || '';

		return '<article class="wordai-sc-opportunity-card is-' + esc(priority) + '">' +
			'<div class="wordai-sc-opportunity-main">' +
				'<div>' +
					'<span class="wordai-sc-priority">' + esc(priority === 'high' ? 'High priority' : (priority === 'watch' ? 'Watch' : 'Medium priority')) + '</span>' +
					'<strong>' + esc(title || 'Untitled page') + '</strong>' +
					'<small>' + esc(pageUrl) + '</small>' +
				'</div>' +
				'<span class="wordai-sc-drop">-' + esc(formatNumber(item.drop_percent)) + '% clicks</span>' +
			'</div>' +
			'<div class="wordai-sc-metric-strip">' +
				metricPill('Previous clicks', formatNumber(item.previous_clicks)) +
				metricPill('Current clicks', formatNumber(item.current_clicks)) +
				metricPill('Click drop', formatNumber(item.click_drop)) +
				metricPill('Current position', formatNumber(item.current_position)) +
			'</div>' +
			'<p class="wordai-sc-opportunity-copy">Refresh the content, review SEO metadata, and rescan after updates to recover search visibility.</p>' +
			opportunityActions(localPost, pageUrl) +
		'</article>';
	}

	function cannibalizationCard(item) {
		var pages = item.pages || [];
		var pageList = pages.length ? '<ul class="wordai-sc-competing-pages">' + pages.map(function (page) {
			var localPost = page.local_post || null;
			var label = localPost && localPost.title ? localPost.title : page.page;
			return '<li><span>' + esc(label || 'Page') + '</span><small>' + esc(formatNumber(page.impressions)) + ' impressions · position ' + esc(formatNumber(page.position)) + '</small></li>';
		}).join('') + '</ul>' : '<div class="wordai-sc-empty">No competing page URLs were returned yet.</div>';

		return '<article class="wordai-sc-opportunity-card">' +
			'<div class="wordai-sc-opportunity-main">' +
				'<div>' +
					'<span class="wordai-sc-priority">Competing query</span>' +
					'<strong>' + esc(item.query || 'Unknown query') + '</strong>' +
					'<small>Multiple indexed pages are competing for this search phrase.</small>' +
				'</div>' +
				'<span class="wordai-sc-drop">' + esc(formatNumber(item.competing_pages)) + ' pages</span>' +
			'</div>' +
			'<div class="wordai-sc-metric-strip">' +
				metricPill('Impressions', formatNumber(item.impressions)) +
				metricPill('Competing pages', formatNumber(item.competing_pages)) +
			'</div>' +
			pageList +
		'</article>';
	}

	function load() {
		showLoading(true);
		request('status').done(function (response) {
			if (response.success) {
				render(response.data);
			} else {
				notice(response.data && response.data.message ? response.data.message : 'Unable to load Search Console.', true);
			}
		}).fail(function (xhr) {
			notice(errorMessage(xhr), true);
		}).always(function () {
			showLoading(false);
		});
	}

	$(document).on('click', '.wordai-sc-tab', function () {
		var tabName = $(this).data('tab');
		$('.wordai-sc-tab').removeClass('is-active');
		$(this).addClass('is-active');
		$('.wordai-sc-panel').removeClass('is-active').filter('[data-panel="' + tabName + '"]').addClass('is-active');
	});

	$('#wordai-sc-refresh').on('click', load);

	$(document).on('click', '.wordai-sc-refresh-properties', function () {
		var button = $(this).prop('disabled', true);
		request('refresh_properties').done(function (response) {
			if (response.success) {
				notice('Search Console properties refreshed.');
				load();
			}
		}).fail(function (xhr) {
			notice(errorMessage(xhr), true);
		}).always(function () {
			button.prop('disabled', false);
		});
	});

	$('#wordai-sc-connect').on('click', function () {
		var popup = window.open('about:blank', 'wordaiSearchConsole', 'width=720,height=760');
		request('connect', {
			marketing_opt_in: $('#wordai-sc-marketing-consent').is(':checked') ? 1 : 0
		}).done(function (response) {
			if (response.success && response.data.authorization_url) {
				if (popup) {
					popup.location = response.data.authorization_url;
				} else {
					window.location.href = response.data.authorization_url;
				}
			} else {
				if (popup) {
					popup.close();
				}
				notice(response.data && response.data.message ? response.data.message : 'Connection could not start.', true);
			}
		}).fail(function (xhr) {
			if (popup) {
				popup.close();
			}
			notice(errorMessage(xhr), true);
		});
	});

	$(document).on('change.wordaiSearchConsoleProvider', '#sc-wordai-ai-provider.sc-wordai-ai-provider-select', function () {
		var select = $(this);
		var previous = String(select.attr('data-provider') || cfg.activeProvider || 'openai');
		var provider = String(select.val() || previous);

		if (!cfg.providerNonce || provider === previous) {
			return;
		}

		select.prop('disabled', true);
		$.post(cfg.ajaxUrl, {
			action: 'sc_wordai_ai_provider_save',
			security: cfg.providerNonce,
			provider: provider
		}).done(function (response) {
			if (!response || response.status !== 'success') {
				select.val(previous);
				notice((response && response.message) ? response.message : 'AI provider could not be changed.', true);
				return;
			}

			cfg.activeProvider = provider;
			$('select.sc-wordai-ai-provider-select').val(provider).attr('data-provider', provider);
			if (typeof window.scWordaiSyncProviderPickerIcons === 'function') {
				window.scWordaiSyncProviderPickerIcons(provider);
			}
			showProviderSwitchDialog(
				provider,
				function () {
					window.location.reload(true);
				},
				function () {
					cfg.activeProvider = previous;
					$('select.sc-wordai-ai-provider-select').val(previous).attr('data-provider', previous);
					if (typeof window.scWordaiSyncProviderPickerIcons === 'function') {
						window.scWordaiSyncProviderPickerIcons(previous);
					}
					$.post(cfg.ajaxUrl, {
						action: 'sc_wordai_ai_provider_save',
						security: cfg.providerNonce,
						provider: previous
					});
				}
			);
		}).fail(function (xhr) {
			select.val(previous);
			if (typeof window.scWordaiSyncProviderPickerIcons === 'function') {
				window.scWordaiSyncProviderPickerIcons(previous);
			}
			notice(errorMessage(xhr), true);
		}).always(function () {
			select.prop('disabled', false);
		});
	});

	$(document).on('click', '.wordai-sc-toggle-property', function () {
		var button = $(this).prop('disabled', true);
		var selected = Number(button.data('selected')) === 1;
		request('select_property', {
			property_id: button.data('id'),
			selected: selected ? 1 : 0
		}).done(function (response) {
			if (response.success) {
				notice(selected ? 'Search Console property selected.' : 'Search Console property deselected.');
				load();
			}
		}).fail(function (xhr) {
			notice(errorMessage(xhr), true);
		}).always(function () {
			button.prop('disabled', false);
		});
	});

	$('#wordai-sc-sync').on('click', function () {
		var button = $(this).prop('disabled', true);
		request('sync').done(function (response) {
			if (response.success) {
				notice('Search Console synchronization is queued. Reports will update after the background job finishes.');
				load();
			}
		}).fail(function (xhr) {
			notice(errorMessage(xhr), true);
		}).always(function () {
			button.prop('disabled', false);
		});
	});

	$('#wordai-sc-disconnect').on('click', function () {
		if (!window.confirm('Disconnect Google Search Console from this WordAI installation?')) {
			return;
		}
		request('disconnect').done(function (response) {
			if (response.success) {
				notice('Google Search Console disconnected.');
				load();
			}
		}).fail(function (xhr) {
			notice(errorMessage(xhr), true);
		});
	});

	window.addEventListener('message', function (event) {
		if (event.data && event.data.type === 'softcoy-search-console') {
			pendingCallbackNotice = {
				message: event.data.message || (event.data.success ? 'Google Search Console is connected.' : 'Google Search Console connection could not be completed.'),
				error: !event.data.success
			};
			notice(pendingCallbackNotice.message, pendingCallbackNotice.error);
			load();
		}
	});

	$(load);
})(jQuery);
