/* ==========================================================================
   SEOvault AI — Admin JavaScript
   ========================================================================== */

(function($) {
	'use strict';

	// Wrap WP list table checkboxes with our styled checkbox overlay
	function styleListTableCheckboxes() {
		$('.widefat .check-column input[type="checkbox"]').each(function() {
			var $cb = $(this);
			if ( $cb.closest('.seovaultseo-check').length ) {
				return;
			}
			var id = $cb.attr('id');
			var attrs = '';
			if ( id ) {
				attrs = ' for="' + id.replace( /"/g, '&quot;' ) + '"';
			}
			$cb.wrap('<label class="seovaultseo-check"' + attrs + '></label>');
			$cb.after('<span></span>');
		});
	}

	$(document).ready(function() {
		styleListTableCheckboxes();
	});

	$(document).on('wp_list_table_init', function() {
		styleListTableCheckboxes();
	});

	// Security tab: jump to API Activity with visible feedback
	$(document).on('click', '.seovaultseo-jump-to-api-activity', function(e) {
		var target = document.getElementById('seovaultseo-security-activity');
		if (!target) {
			return;
		}

		e.preventDefault();
		if (typeof target.scrollIntoView === 'function') {
			target.scrollIntoView({ behavior: 'smooth', block: 'start' });
		}
		target.classList.remove('is-highlighted');
		// Force reflow so the highlight animation can replay.
		void target.offsetWidth;
		target.classList.add('is-highlighted');
		window.setTimeout(function() {
			target.classList.remove('is-highlighted');
		}, 1400);

		if (window.history && typeof window.history.replaceState === 'function') {
			try {
				var url = new URL(window.location.href);
				url.hash = 'seovaultseo-security-activity';
				window.history.replaceState(null, '', url.toString());
			} catch (err) {
				// Older browsers: ignore hash update failures.
			}
		}
	});

	// Copy site key to clipboard
	$(document).on('click', '.seovaultseo-copy-key', function(e) {
		e.preventDefault();
		var key = $(this).data('key');
		if (!key) {
			return;
		}

		var $temp = $('<input>').attr('type', 'text').val(key);
		$('body').append($temp);
		$temp.select();
		try {
			document.execCommand('copy');
			var $btn = $(this);
			var originalHtml = $btn.html();
			$btn.html('<span class="dashicons dashicons-yes-alt"></span> ' + seovaultseo_admin_vars.copied_text);
			setTimeout(function() {
				$btn.html(originalHtml);
			}, 2000);
		} catch (err) {
			// Fallback
		}
		$temp.remove();
	});

	// Handle admin actions (regenerate key, save llms settings)
	if (typeof seovaultseo_admin !== 'undefined') {
		// Localize the copied text
		window.seovaultseo_admin_vars = {
			copied_text: seovaultseo_admin.copied_text || 'Copied!'
		};
	} else {
		window.seovaultseo_admin_vars = {
			copied_text: 'Copied!'
		};
	}

	$(document).on('click', '#seovaultseo-save-all-settings-btn', function(e) {
		var mainForm = document.getElementById('seovaultseo-general-form');
		if (!mainForm) {
			return;
		}

		e.preventDefault();

		var button = this;
		var activeTabInput = document.getElementById('seovaultseo-active-tab');
		var activeTab = activeTabInput && activeTabInput.value ? activeTabInput.value : window.location.hash.replace(/^#/, '');
		if (!activeTab) {
			activeTab = 'vtab-connection';
		}

		var actionUrl = (mainForm.getAttribute('action') || window.location.href).replace(/#.*$/, '');
		try {
			var parsed = new URL(actionUrl, window.location.origin);
			parsed.searchParams.set('tab', activeTab);
			parsed.hash = activeTab;
			actionUrl = parsed.pathname + parsed.search + parsed.hash;
		} catch (err) {
			actionUrl = actionUrl.replace(/([?&]tab=)[^&]*/i, '$1' + encodeURIComponent(activeTab));
			if (actionUrl.indexOf('tab=') === -1) {
				actionUrl += (actionUrl.indexOf('?') === -1 ? '?' : '&') + 'tab=' + encodeURIComponent(activeTab);
			}
			actionUrl += '#' + activeTab;
		}
		var tempForm = document.createElement('form');
		tempForm.method = 'post';
		tempForm.action = actionUrl;
		tempForm.style.display = 'none';

		function appendHidden(name, value) {
			var input = document.createElement('input');
			input.type = 'hidden';
			input.name = name;
			input.value = value;
			tempForm.appendChild(input);
		}

		function isAllowedNestedField(name) {
			return name === 'seovaultseo_llms_enabled' || name.indexOf('seovaultseo_local_settings[') === 0;
		}

		function shouldIncludeField(field) {
			if (!field || !field.name || field.disabled) {
				return false;
			}

			var type = (field.type || '').toLowerCase();
			if (type === 'submit' || type === 'button' || type === 'reset' || type === 'file') {
				return false;
			}

			if (field.name === '_wpnonce' || field.name === '_wp_http_referer' || field.name === 'option_page' || field.name === 'action') {
				return false;
			}

			var ownerForm = field.closest('form');
			if (ownerForm && ownerForm !== mainForm && !isAllowedNestedField(field.name)) {
				return false;
			}

			return true;
		}

		appendHidden('_wpnonce', mainForm.querySelector('input[name="_wpnonce"]') ? mainForm.querySelector('input[name="_wpnonce"]').value : '');
		appendHidden('_wp_http_referer', window.location.pathname + window.location.search);
		appendHidden('seovaultseo_save_all_settings', '1');
		appendHidden('seovaultseo_active_tab', activeTab);

		// Collect from all tab panels in the wrapper (not only .seovaultseo-vtab-content)
		// because nested forms can close the main form early in the DOM.
		var fields = document.querySelectorAll('.seovaultseo-vtab-wrapper .seovaultseo-vtab-panel input, .seovaultseo-vtab-wrapper .seovaultseo-vtab-panel select, .seovaultseo-vtab-wrapper .seovaultseo-vtab-panel textarea');
		Array.prototype.forEach.call(fields, function(field) {
			if (!shouldIncludeField(field)) {
				return;
			}

			var tagName = field.tagName.toLowerCase();
			var type = (field.type || '').toLowerCase();
			if ((type === 'checkbox' || type === 'radio') && !field.checked) {
				return;
			}

			if (tagName === 'select' && field.multiple) {
				Array.prototype.forEach.call(field.options, function(option) {
					if (option.selected) {
						appendHidden(field.name, option.value);
					}
				});
				return;
			}

			appendHidden(field.name, field.value);
		});

		if (typeof seovaultseo_admin !== 'undefined' && seovaultseo_admin.ajax_url && seovaultseo_admin.nonce) {
			try {
				var payload = new URLSearchParams({
					action: 'seovaultseo_log_save_all_settings_click',
					nonce: seovaultseo_admin.nonce,
					active_tab: activeTab
				});

				if (navigator.sendBeacon) {
					navigator.sendBeacon(seovaultseo_admin.ajax_url, payload);
				} else {
					$.post(seovaultseo_admin.ajax_url, payload.toString());
				}
			} catch (err) {
				// Continue with submit even if click logging fails.
			}
		}

		button.disabled = true;
		document.body.appendChild(tempForm);
		tempForm.submit();
	});

	// Migration: batch import with progress bar
	$(document).on('click', '.seovaultseo-migrate-btn', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var provider = $btn.data('provider');
		var total = parseInt($btn.data('total'), 10) || 0;
		var $container = $btn.closest('.seovaultseo-migration-provider');
		var $progress = $container.find('.seovaultseo-migration-progress');
		var $fill = $container.find('.seovaultseo-progress-fill');
		var $text = $container.find('.seovaultseo-progress-text');
		var $log = $container.find('.seovaultseo-migration-log');

		$btn.prop('disabled', true);
		$progress.show();
		$log.html('');

		var processed = 0;
		var imported = 0;
		var failed = 0;
		var offset = 0;
		var currentType = 'posts';

		function updateProgress() {
			var pct = total > 0 ? Math.min(100, Math.round((processed / total) * 100)) : 0;
			$fill.css('width', pct + '%');
			$text.text(processed + ' / ' + total);
		}

		function importBatch() {
			$.ajax({
				url: seovaultseo_admin.ajax_url,
				method: 'POST',
				data: {
					action: 'seovaultseo_migration_import',
					nonce: seovaultseo_admin.nonce,
					provider: provider,
					offset: offset,
					type: currentType
				},
				success: function(response) {
					if (response.success && response.data) {
						var d = response.data;
						imported += d.imported || 0;
						failed += d.failed || 0;
						processed += (d.imported || 0) + (d.failed || 0);
						offset = d.offset || 0;

						if (d.log && d.log.length) {
							for (var i = 0; i < d.log.length; i++) {
								$log.append($('<div>').text(d.log[i]));
							}
						}

						updateProgress();

						if (d.has_more) {
							setTimeout(importBatch, 300);
						} else if (currentType === 'posts') {
							// Switch to terms
							currentType = 'terms';
							offset = 0;
							setTimeout(importBatch, 300);
						} else {
							// Done
							$log.append('<div style="margin-top:10px;font-weight:bold;">' + (seovaultseo_admin.migration_complete || '=== Migration Complete ===') + '</div>');
							$log.append('<div>' + (seovaultseo_admin.migration_imported_label || 'Imported: ') + imported + (seovaultseo_admin.migration_skipped_label || ' | Skipped: ') + failed + '</div>');
							$btn.prop('disabled', false);
						}
					} else {
						var errMsg = (response.data && response.data.message) || (seovaultseo_admin.error_unknown || 'Unknown error');
						$log.append('<div style="color:red;">' + (seovaultseo_admin.migration_error || 'Error: ') + errMsg + '</div>');
						$btn.prop('disabled', false);
					}
				},
				error: function(xhr, status, error) {
					$log.append('<div style="color:red;">' + (seovaultseo_admin.migration_ajax_error || 'AJAX Error: ') + error + '</div>');
					$btn.prop('disabled', false);
				}
			});
		}

		importBatch();
	});

	// Migration: import global settings
	$(document).on('click', '.seovaultseo-migrate-global-btn', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var provider = $btn.data('provider');
		var $container = $btn.closest('.seovaultseo-migration-provider');
		var $log = $container.find('.seovaultseo-migration-log');

		$btn.prop('disabled', true);
		$container.find('.seovaultseo-migration-progress').show();

		$.ajax({
			url: seovaultseo_admin.ajax_url,
			method: 'POST',
			data: {
				action: 'seovaultseo_migration_import',
				nonce: seovaultseo_admin.nonce,
				provider: provider,
				offset: 0,
				type: 'global'
			},
			success: function(response) {
				if (response.success) {
					$log.append('<div>' + (seovaultseo_admin.migration_global_imported || 'Global settings imported successfully.') + '</div>');
				} else {
					$log.append('<div>' + (seovaultseo_admin.migration_no_global_found || 'No global settings found to import.') + '</div>');
				}
				$btn.prop('disabled', false);
			},
			error: function(xhr, status, error) {
				$log.append('<div style="color:red;">' + (seovaultseo_admin.migration_ajax_error || 'AJAX Error: ') + error + '</div>');
				$btn.prop('disabled', false);
			}
		});
	});

	// Third-party FAQ/HowTo block conversion (Yoast / Rank Math) — Tools tab.
	var thirdPartyScanTotal = 0;
	$(document).on('click', '#seovault-thirdparty-block-scan-btn', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var $summary = $('#seovault-thirdparty-block-summary');
		var $convertBtn = $('#seovault-thirdparty-block-convert-btn');
		$btn.prop('disabled', true);
		$summary.hide().empty();
		$convertBtn.prop('disabled', true);

		$.post(seovaultseo_admin.ajax_url, {
			action: 'seovaultseo_thirdparty_block_scan',
			nonce: seovaultseo_admin.nonce
		}).done(function(response) {
			$btn.prop('disabled', false);
			if (!response.success || !response.data) {
				$summary.show().html('<div class="notice notice-error inline"><p>' + (seovaultseo_admin.error_unknown || 'Scan failed.') + '</p></div>');
				return;
			}
			var d = response.data;
			thirdPartyScanTotal = parseInt(d.post_total, 10) || 0;
			var rmPosts = (d.by_plugin && d.by_plugin.rankmath && d.by_plugin.rankmath.posts) ? d.by_plugin.rankmath.posts : 0;
			var yoastPosts = (d.by_plugin && d.by_plugin.yoast && d.by_plugin.yoast.posts) ? d.by_plugin.yoast.posts : 0;
			var rmBlocks = (d.by_plugin && d.by_plugin.rankmath && d.by_plugin.rankmath.blocks) ? d.by_plugin.rankmath.blocks : 0;
			var yoastBlocks = (d.by_plugin && d.by_plugin.yoast && d.by_plugin.yoast.blocks) ? d.by_plugin.yoast.blocks : 0;
			var html = '<div class="notice notice-info inline"><p>' +
				'<strong>Posts with Rank Math blocks:</strong> ' + rmPosts + ' (' + rmBlocks + ' blocks)<br>' +
				'<strong>Posts with Yoast blocks:</strong> ' + yoastPosts + ' (' + yoastBlocks + ' blocks)<br>' +
				'<strong>Total posts with blocks:</strong> ' + thirdPartyScanTotal + '<br>' +
				'<strong>Convertible blocks (sampled):</strong> ' + (d.convertible_count || 0) + '<br>' +
				'<strong>Blocked blocks (sampled):</strong> ' + (d.blocked_count || 0);
			html += '</p></div>';
			$summary.show().html(html);
			$convertBtn.prop('disabled', thirdPartyScanTotal <= 0);
		}).fail(function() {
			$btn.prop('disabled', false);
			$summary.show().html('<div class="notice notice-error inline"><p>' + (seovaultseo_admin.migration_ajax_error || 'Scan request failed.') + '</p></div>');
		});
	});

	$(document).on('click', '#seovault-thirdparty-block-convert-btn', function(e) {
		e.preventDefault();
		if (thirdPartyScanTotal <= 0) {
			return;
		}
		if (!window.confirm('Convert all found FAQ and How-to blocks to SEOvault blocks? A backup is saved per post.')) {
			return;
		}

		var $btn = $(this);
		var $scanBtn = $('#seovault-thirdparty-block-scan-btn');
		var $progress = $('#seovault-thirdparty-block-progress');
		var $log = $('#seovault-thirdparty-block-log');
		var convertedPosts = 0;
		var convertedBlocks = 0;
		var failed = 0;
		var startingTotal = thirdPartyScanTotal;

		$btn.prop('disabled', true);
		$scanBtn.prop('disabled', true);
		$progress.show();
		$log.html('');

		function appendLog(text) {
			$log.append($('<div>').text(text));
			$log.scrollTop($log[0].scrollHeight);
		}

		function convertBatch() {
			$.post(seovaultseo_admin.ajax_url, {
				action: 'seovaultseo_thirdparty_block_convert_batch',
				nonce: seovaultseo_admin.nonce,
				confirm: 1,
				limit: 10
			}).done(function(response) {
				if (!response.success || !response.data) {
					var err = (response.data && response.data.message) ? response.data.message : (seovaultseo_admin.error_unknown || 'Batch conversion failed.');
					appendLog(err);
					$btn.prop('disabled', false);
					$scanBtn.prop('disabled', false);
					return;
				}
				var d = response.data;
				convertedPosts += d.converted_posts || 0;
				convertedBlocks += d.converted_blocks || 0;
				failed += d.failed || 0;
				appendLog(
					'Batch: converted ' + (d.converted_posts || 0) + ' posts / ' + (d.converted_blocks || 0) +
					' blocks. Remaining: ' + (d.remaining || 0)
				);

				if (d.has_more) {
					setTimeout(convertBatch, 300);
				} else {
					appendLog('=== Conversion Complete ===');
					appendLog('Posts converted: ' + convertedPosts + ' | Blocks: ' + convertedBlocks + ' | Failed: ' + failed + ' | Started with: ' + startingTotal);
					thirdPartyScanTotal = d.remaining || 0;
					$btn.prop('disabled', thirdPartyScanTotal > 0);
					$scanBtn.prop('disabled', false);
				}
			}).fail(function(xhr, status, error) {
				appendLog((seovaultseo_admin.migration_ajax_error || 'AJAX Error: ') + error);
				$btn.prop('disabled', false);
				$scanBtn.prop('disabled', false);
			});
		}

		convertBatch();
	});

	function collectSchemaV2Settings($root) {
		var automatic = {};
		$root.find('.seovaultseo-schema-v2-automatic').each(function() {
			var key = $(this).data('automatic-key');
			if (key) {
				automatic[key] = $(this).is(':checked');
			}
		});

		return {
			schema_enabled: $root.find('[data-v2-field="schema_enabled"]').is(':checked') ? 'yes' : 'no',
			publisher_identity: $root.find('[data-v2-field="publisher_identity"]').val() || 'organization',
			automatic: automatic,
			catalogue: {
				show_extension_types: $root.find('[data-v2-field="catalogue_show_extension_types"]').is(':checked')
			},
			settings_revision: parseInt($root.attr('data-settings-revision') || '0', 10) || 0
		};
	}

	function showSchemaV2Notice(message, isError) {
		var $notices = $('#seovaultseo-schema-v2-notices');
		if (!$notices.length) {
			return;
		}
		var className = isError ? 'notice notice-error inline' : 'notice notice-success inline';
		var role = isError ? 'alert' : 'status';
		$notices.html('<div class="' + className + '" role="' + role + '"><p>' + $('<div>').text(message || '').html() + '</p></div>');
	}

	$(document).on('click', '#seovaultseo-save-schema-v2', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var $root = $('#seovaultseo-schema-settings-v2');
		var $msg = $('#seovaultseo-schema-v2-saved-msg');

		if (!$root.length || typeof seovaultseo_admin === 'undefined') {
			return;
		}

		var settings = collectSchemaV2Settings($root);
		var saveLabel = $btn.text();
		$btn.prop('disabled', true).attr('aria-busy', 'true').text(seovaultseo_admin.schema_v2_saving || 'Saving…');
		showSchemaV2Notice('', false);

		$.ajax({
			url: seovaultseo_admin.ajax_url,
			method: 'POST',
			data: {
				action: 'seovaultseo_save_schema_v2_settings',
				nonce: seovaultseo_admin.nonce,
				settings: JSON.stringify(settings),
				settings_revision: settings.settings_revision
			},
			success: function(response) {
				$btn.prop('disabled', false).removeAttr('aria-busy').text(saveLabel);
				if (response && response.success && response.data) {
					if (typeof response.data.settings_revision !== 'undefined') {
						$root.attr('data-settings-revision', String(response.data.settings_revision));
					}
					$msg.show().delay(2000).fadeOut(400);
					showSchemaV2Notice(response.data.message || seovaultseo_admin.schema_v2_saved || 'Saved!', false);
					return;
				}

				var errMessage = (response && response.data && response.data.message)
					|| (seovaultseo_admin.schema_v2_save_failed || seovaultseo_admin.save_failed || 'Save failed.');
				if (response && response.data && response.data.code === 'schema_settings_stale') {
					errMessage = response.data.message || seovaultseo_admin.schema_v2_stale || errMessage;
					if (response.data.settings && typeof response.data.settings.settings_revision !== 'undefined') {
						$root.attr('data-settings-revision', String(response.data.settings.settings_revision));
					}
				}
				showSchemaV2Notice(errMessage, true);
			},
			error: function(xhr) {
				$btn.prop('disabled', false).removeAttr('aria-busy').text(saveLabel);
				var errMessage = seovaultseo_admin.schema_v2_save_failed || seovaultseo_admin.save_failed || 'Save failed.';
				if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
					errMessage = xhr.responseJSON.data.message;
				}
				showSchemaV2Notice(errMessage, true);
			}
		});
	});

	// Schema Templates: toggle and load via AJAX
	function setSchemaTemplatesToggleLabel($btn, visible) {
		var label = visible
			? ($btn.data('label-hide') || (seovaultseo_admin.schema_templates_hide || 'Hide Schema Templates'))
			: ($btn.data('label-show') || (seovaultseo_admin.schema_templates_show || 'Show Schema Templates'));
		$btn.contents().filter(function() {
			return this.nodeType === 3;
		}).each(function() {
			this.textContent = ' ' + label + ' ';
		});
	}

	$(document).on('click', '#seovaultseo-schema-templates-toggle', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var $container = $('#seovaultseo-schema-templates-container');
		var $icon = $btn.find('.dashicons');
		var loaded = $btn.data('loaded') === true;

		if ($container.is(':visible')) {
			$container.slideUp(200);
			setSchemaTemplatesToggleLabel($btn, false);
			$icon.removeClass('dashicons-arrow-up-alt2').addClass('dashicons-feedback');
			return;
		}

		if (!loaded) {
			$btn.prop('disabled', true);
			$.ajax({
				url: seovaultseo_admin.ajax_url,
				method: 'POST',
				data: {
					action: 'seovaultseo_schema_list_templates',
					nonce: seovaultseo_admin.nonce
				},
				success: function(response) {
					$btn.prop('disabled', false);
					if (response.success && response.data.html) {
						$container.html(response.data.html);
						$btn.data('loaded', true);
						setSchemaTemplatesToggleLabel($btn, true);
						$icon.removeClass('dashicons-feedback').addClass('dashicons-arrow-up-alt2');
						$container.slideDown(200);
					} else {
						alert(response.data && response.data.message || (seovaultseo_admin.templates_load_failed || 'Failed to load templates.'));
					}
				},
				error: function() {
					$btn.prop('disabled', false);
					alert(seovaultseo_admin.templates_load_failed || 'Failed to load templates.');
				}
			});
		} else {
			setSchemaTemplatesToggleLabel($btn, true);
			$icon.removeClass('dashicons-feedback').addClass('dashicons-arrow-up-alt2');
			$container.slideDown(200);
		}
	});

	// Social Image Media Uploader
	$(document).on('click', '#seovaultseo-social-image-upload', function(e) {
		e.preventDefault();
		if (typeof wp === 'undefined' || !wp.media) {
			return;
		}
		var frame = wp.media({
			title: (seovaultseo_admin.select_default_social_image || 'Select Default Social Image'),
			button: { text: (seovaultseo_admin.set_default_image || 'Set Default Image') },
			multiple: false
		});
		frame.on('select', function() {
			var attachment = frame.state().get('selection').first().toJSON();
			var url = attachment.url;
			$('#seovaultseo_default_social_image').val(url);
			$('#seovaultseo-social-image-url').val(url);
			var $preview = $('#seovaultseo-social-image-preview');
			$preview.empty().append(
				$('<img>')
					.attr('src', url)
					.attr('alt', seovaultseo_admin.social_image_alt || 'Social Image')
					.css({ maxWidth: '100%', maxHeight: '280px', borderRadius: '6px' })
			);
			$('#seovaultseo-social-image-remove').show();
		});
		frame.open();
	});

	// Remove social image
	$(document).on('click', '#seovaultseo-social-image-remove', function(e) {
		e.preventDefault();
		$('#seovaultseo_default_social_image').val('');
		$('#seovaultseo-social-image-url').val('');
		var $preview = $('#seovaultseo-social-image-preview');
		$preview.empty().append(
			$('<span>')
				.addClass('dashicons dashicons-format-image')
				.css({ fontSize: '48px', width: '48px', height: '48px', color: '#ccc' })
		);
		$(this).hide();
	});

	// Sync URL text input with hidden field
	$(document).on('input', '#seovaultseo-social-image-url', function() {
		var url = $(this).val();
		$('#seovaultseo_default_social_image').val(url);
		if (url) {
			$('#seovaultseo-social-image-preview').empty().append(
				$('<img>')
					.attr('src', url)
					.attr('alt', seovaultseo_admin.social_image_alt || 'Social Image')
					.css({ maxWidth: '100%', maxHeight: '280px', borderRadius: '6px' })
			);
			$('#seovaultseo-social-image-remove').show();
		} else {
			$('#seovaultseo-social-image-preview').empty().append(
				$('<span>')
					.addClass('dashicons dashicons-format-image')
					.css({ fontSize: '48px', width: '48px', height: '48px', color: '#ccc' })
			);
			$('#seovaultseo-social-image-remove').hide();
		}
	});

	// Add new social profile row
	$(document).on('click', '#seovaultseo-add-profile', function(e) {
		e.preventDefault();
		var $container = $('#seovaultseo-social-profiles-container');
		var $newRow = $('<div class="seovaultseo-social-profile-row" style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">' +
			'<input type="url" name="seovaultseo_social_profiles[]" value="" class="regular-text" placeholder="' + (seovaultseo_admin.url_placeholder || 'https://...') + '" />' +
			'<button type="button" class="button button-secondary seovaultseo-remove-profile"><span class="dashicons dashicons-trash"></span></button>' +
			'</div>');
		$container.append($newRow);
		$newRow.find('input').focus();
	});

	// Remove social profile row
	$(document).on('click', '.seovaultseo-remove-profile', function(e) {
		e.preventDefault();
		var $container = $(this).closest('#seovaultseo-social-profiles-container');
		if ($container.find('.seovaultseo-social-profile-row').length > 1) {
			$(this).closest('.seovaultseo-social-profile-row').remove();
		} else {
			$(this).closest('.seovaultseo-social-profile-row').find('input').val('');
		}
	});

	/* ==========================================================================
	   Custom Select Dropdown Component
	   Transforms <select class="seovaultseo-select"> into a styled dropdown
	   ========================================================================== */

	var arrowSvg = '<svg viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2 4l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
	var checkSvg = '<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M3 8l3.5 3.5L13 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';

	function initSelect($select) {
		if ($select.data('seovaultseo-select-initialized')) {
			return;
		}
		$select.data('seovaultseo-select-initialized', true);

		var selectId = $select.attr('id') || '';
		var selectName = $select.attr('name') || '';
		var selectedVal = $select.val() || '';
		var $options = $select.find('option');

		// Determine width class
		var widthClass = 'seovaultseo-select-regular';
		if ($select.hasClass('large-text') || $select.hasClass('seovaultseo-select-large')) {
			widthClass = 'seovaultseo-select-large';
		} else if ($select.hasClass('small-text') || $select.hasClass('seovaultseo-select-small')) {
			widthClass = 'seovaultseo-select-small';
		}

		// Build wrapper
		var $wrapper = $('<div>', {
			class: 'seovaultseo-select-wrapper ' + widthClass
		});

		// Build trigger
		var $trigger = $('<div>', {
			class: 'seovaultseo-select-trigger',
			tabindex: 0,
			role: 'combobox',
			'aria-haspopup': 'listbox',
			'aria-expanded': 'false'
		});
		if (selectId) {
			$trigger.attr('aria-labelledby', selectId + '-label');
		}

		var $label = $('<span>', { class: 'seovaultseo-select-label' });
		var $arrow = $('<span>', { class: 'seovaultseo-select-arrow', html: arrowSvg });
		$trigger.append($label, $arrow);

		// Build dropdown
		var $dropdown = $('<div>', {
			class: 'seovaultseo-select-dropdown',
			role: 'listbox',
			'aria-label': seovaultseo_admin.select_options_label || 'Options'
		});

		var optionData = [];
		$options.each(function() {
			var val = $(this).attr('value');
			var text = $(this).text();
			var isSelected = (val === selectedVal) || (!selectedVal && $(this).prop('selected'));
			optionData.push({ value: val, text: text, selected: isSelected });

			var $opt = $('<div>', {
				class: 'seovaultseo-select-option' + (isSelected ? ' seovaultseo-select-selected' : ''),
				'data-value': val,
				role: 'option',
				'aria-selected': isSelected ? 'true' : 'false'
			});
			$opt.append($('<span>', { class: 'seovaultseo-select-option-text', text: text }));
			$opt.append($('<span>', { class: 'seovaultseo-select-check', html: checkSvg }));
			$dropdown.append($opt);
		});

		// Set initial label
		var selectedOpt = optionData.find(function(o) { return o.selected; });
		$label.text(selectedOpt ? selectedOpt.text : (optionData.length ? optionData[0].text : ''));

		// Hide native select but keep it for form submission
		$select.addClass('seovaultseo-select-native');
		$select.attr('tabindex', '-1');

		$wrapper.append($trigger, $dropdown);
		$select.after($wrapper);
		$wrapper.append($select);

		// --- Event handlers ---

		var isOpen = false;
		var highlightIndex = -1;

		function open() {
			isOpen = true;
			$trigger.addClass('seovaultseo-select-open');
			$dropdown.addClass('seovaultseo-select-dropdown-open');
			$trigger.attr('aria-expanded', 'true');
			// Scroll to selected
			var $sel = $dropdown.find('.seovaultseo-select-selected');
			if ($sel.length) {
				highlightIndex = $dropdown.find('.seovaultseo-select-option').index($sel);
				$sel[0].scrollIntoView({ block: 'nearest' });
			}
		}

		function close() {
			isOpen = false;
			$trigger.removeClass('seovaultseo-select-open');
			$dropdown.removeClass('seovaultseo-select-dropdown-open');
			$trigger.attr('aria-expanded', 'false');
		}

		function toggle() {
			if (isOpen) { close(); } else { open(); }
		}

		function selectOption(val, text) {
			$select.val(val).trigger('change');
			$label.text(text);
			$dropdown.find('.seovaultseo-select-option').removeClass('seovaultseo-select-selected').attr('aria-selected', 'false');
			var $opt = $dropdown.find('.seovaultseo-select-option[data-value="' + val.replace(/"/g, '\\"') + '"]');
			$opt.addClass('seovaultseo-select-selected').attr('aria-selected', 'true');
			highlightIndex = $dropdown.find('.seovaultseo-select-option').index($opt);
		}

		function highlight(idx) {
			var $opts = $dropdown.find('.seovaultseo-select-option');
			if (idx < 0) idx = $opts.length - 1;
			if (idx >= $opts.length) idx = 0;
			$opts.removeClass('seovaultseo-select-highlighted');
			$opts.eq(idx).addClass('seovaultseo-select-highlighted');
			$opts[idx].scrollIntoView({ block: 'nearest' });
			highlightIndex = idx;
		}

		$trigger.on('click', function(e) {
			e.stopPropagation();
			toggle();
		});

		$trigger.on('keydown', function(e) {
			if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
				e.preventDefault();
				if (!isOpen) { open(); }
				else if (e.key === 'ArrowDown') { highlight(highlightIndex + 1); }
			} else if (e.key === 'ArrowUp') {
				e.preventDefault();
				if (isOpen) { highlight(highlightIndex - 1); }
			} else if (e.key === 'Escape') {
				e.preventDefault();
				close();
			} else if (e.key === 'Tab') {
				close();
			}
		});

		$dropdown.on('click', '.seovaultseo-select-option', function() {
			var val = $(this).data('value');
			var text = $(this).find('.seovaultseo-select-option-text').text();
			selectOption(val, text);
			close();
			$trigger.focus();
		});

		$dropdown.on('mouseenter', '.seovaultseo-select-option', function() {
			var $opts = $dropdown.find('.seovaultseo-select-option');
			highlightIndex = $opts.index(this);
			$opts.removeClass('seovaultseo-select-highlighted');
		});

		// Close on outside click
		$(document).on('click', function(e) {
			if (!$(e.target).closest($wrapper).length && isOpen) {
				close();
			}
		});

		// Sync when native select changes programmatically
		$select.on('change', function() {
			var val = $(this).val();
			var text = $(this).find('option[value="' + val.toString().replace(/"/g, '\\"') + '"]').text();
			$label.text(text);
			$dropdown.find('.seovaultseo-select-option').removeClass('seovaultseo-select-selected').attr('aria-selected', 'false');
			$dropdown.find('.seovaultseo-select-option[data-value="' + val.toString().replace(/"/g, '\\"') + '"]').addClass('seovaultseo-select-selected').attr('aria-selected', 'true');
		});
	}

	function initAllSelects($scope) {
		($scope || $(document)).find('select.seovaultseo-select').each(function() {
			initSelect($(this));
		});
	}

	// Expose for dynamic content
	window.seovaultInitSelects = initAllSelects;

	$(document).ready(function() {
		initAllSelects($(document));
	});

	// Re-init on dynamic content load
	$(document).on('seovaultseo_select_reinit', function() {
		initAllSelects($(document));
	});

})(jQuery);
