/**
 * Options Page Builder - Admin JavaScript
 *
 * @package OptionsPageBuilder
 * @since 1.0.0
 */

(function($) {
	'use strict';

	var config = window.wppsOpb || {};
	var currentPageId = null;
	var saveTimeout = null;

	var fieldLabels = {
		text: 'Text', textarea: 'Textarea', select: 'Select', checkbox: 'Checkbox',
		radio: 'Radio', number: 'Number', email: 'Email', url: 'URL', color: 'Color',
		image: 'Image', file: 'File', gallery: 'Gallery', wysiwyg: 'WYSIWYG', date: 'Date',
		message: 'Message', group: 'Section', toggle: 'Toggle', link: 'Link', repeater: 'Repeater'
	};

	var fieldTypeIcons = {
		text: 'M4 6h16M4 12h16m-7 6h7',
		textarea: 'M4 6h16M4 12h16M4 18h7',
		select: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2',
		checkbox: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
		radio: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z',
		number: 'M7 20l4-16m2 16l4-16M6 9h14M4 15h14',
		email: 'M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207',
		url: 'M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1',
		color: 'M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01',
		image: 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z',
		wysiwyg: 'M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z',
		date: 'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z',
		file: 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
		message: 'M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z',
		group: 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10',
		toggle: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
		link: 'M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1',
		gallery: 'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z',
		repeater: 'M4 6h16M4 10h16M4 14h16M4 18h16'
	};

	var widthLabels = { 'full': 'Full', '2-3': '2/3', '1-2': '1/2', '1-3': '1/3' };

	var fallbackDashicons = [
		'dashicons-admin-generic', 'dashicons-admin-settings', 'dashicons-admin-tools',
		'dashicons-admin-site', 'dashicons-admin-appearance', 'dashicons-admin-plugins',
		'dashicons-admin-users', 'dashicons-admin-post', 'dashicons-admin-page',
		'dashicons-admin-media', 'dashicons-admin-comments', 'dashicons-admin-home',
		'dashicons-format-image', 'dashicons-format-gallery', 'dashicons-calendar-alt',
		'dashicons-email', 'dashicons-star-filled', 'dashicons-heart', 'dashicons-groups', 'dashicons-yes'
	];

	function getDashiconsList() {
		if (config.dashicons && config.dashicons.length) {
			return config.dashicons;
		}
		return fallbackDashicons;
	}

	function escapeHtml(s) {
		if (!s) return '';
		var d = document.createElement('div');
		d.textContent = s;
		return d.innerHTML;
	}

	function generateRandomFieldId() {
		return 'field_' + (10000000 + Math.floor(Math.random() * 90000000));
	}

	function showToast(message, type) {
		type = type || 'success';
		$('.wpps-opb-toast').remove();
		var iconSvg = type === 'success'
			? '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>'
			: '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>';
		var $toast = $('<div class="wpps-opb-toast wpps-opb-toast-' + type + '"><span class="wpps-opb-toast-icon">' + iconSvg + '</span><span class="wpps-opb-toast-message">' + escapeHtml(message) + '</span></div>');
		$('body').append($toast);
		setTimeout(function() { $toast.addClass('is-visible'); }, 10);
		setTimeout(function() {
			$toast.removeClass('is-visible');
			setTimeout(function() { $toast.remove(); }, 300);
		}, 3000);
	}

	function updateSaveIndicator(state, text) {
		var $ind = $('#opb-save-indicator');
		$ind.removeClass('is-saving is-saved is-error').empty();
		if (state === 'saving') {
			$ind.addClass('is-saving').html('<span class="wpps-opb-save-spinner"></span> ' + escapeHtml(text || 'Saving...'));
		} else if (state === 'saved') {
			$ind.addClass('is-saved').html('<svg style="width:14px;height:14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg> ' + escapeHtml(text || 'Saved'));
		} else if (state === 'error') {
			$ind.addClass('is-error').text(text || 'Error');
		}
	}

	function closeImportModal() {
		$('#wpps-opb-import-modal').attr('aria-hidden', 'true').removeClass('active').hide();
		$('body').css('overflow', '');
	}

	var defaultPlaceholders = {
		text: 'e.g. Hello', textarea: 'e.g. Multi-line text', number: 'e.g. 42', email: 'e.g. user@example.com',
		url: 'e.g. https://example.com', color: 'e.g. #ff0000', checkbox: '1 = checked, 0 = unchecked',
		select: 'Option value from Options list', radio: 'Option value from Options list',
		wysiwyg: 'Initial HTML content', image: 'Attachment ID (e.g. 123)', date: 'e.g. 2025-01-15'
	};

	function getDefaultInputHtml(type, def, defPlaceholder) {
		def = def || '';
		defPlaceholder = defPlaceholder || defaultPlaceholders[type] || 'Pre-filled when no value saved';
		if (type === 'wysiwyg') {
			return '<textarea class="opb-field-default wpps-opb-input" rows="4" placeholder="' + escapeHtml(defPlaceholder) + '">' + escapeHtml(def) + '</textarea>';
		}
		if (type === 'checkbox' || type === 'toggle') {
			var sel = (def === '1' || def === 'true' || def === 'yes') ? '1' : (def === '0' || def === 'false' || def === 'no') ? '0' : '';
			return '<select class="opb-field-default wpps-opb-select opb-field-default-checkbox">' +
				'<option value=""' + (sel === '' ? ' selected' : '') + '>— None —</option>' +
				'<option value="1"' + (sel === '1' ? ' selected' : '') + '>1 (on)</option>' +
				'<option value="0"' + (sel === '0' ? ' selected' : '') + '>0 (off)</option>' +
				'</select>';
		}
		if (type === 'number') {
			return '<input type="number" class="opb-field-default wpps-opb-input" value="' + escapeHtml(def) + '" placeholder="' + escapeHtml(defPlaceholder) + '">';
		}
		if (type === 'email') {
			return '<input type="email" class="opb-field-default wpps-opb-input" value="' + escapeHtml(def) + '" placeholder="' + escapeHtml(defPlaceholder) + '">';
		}
		if (type === 'url' || type === 'image') {
			return '<input type="url" class="opb-field-default wpps-opb-input" value="' + escapeHtml(def) + '" placeholder="' + escapeHtml(defPlaceholder) + '">';
		}
		if (type === 'color') {
			var hex = (def || '').replace(/^#/, '');
			if (/^[0-9a-fA-F]{6}$/.test(hex)) {
				hex = '#' + hex;
			} else if (/^[0-9a-fA-F]{3}$/.test(hex)) {
				hex = '#' + hex;
			} else {
				hex = def && def.indexOf('#') === 0 ? def : '#808080';
			}
			return '<div class="opb-field-default-color-wrap">' +
				'<input type="color" class="opb-field-default-color" value="' + escapeHtml(hex) + '" title="Pick color">' +
				'<input type="text" class="opb-field-default wpps-opb-input" value="' + escapeHtml(def) + '" placeholder="' + escapeHtml(defPlaceholder) + '" maxlength="7">' +
				'</div>';
		}
		if (type === 'date') {
			return '<input type="date" class="opb-field-default wpps-opb-input" value="' + escapeHtml(def) + '" placeholder="' + escapeHtml(defPlaceholder) + '">';
		}
		return '<input type="text" class="opb-field-default wpps-opb-input" value="' + escapeHtml(def) + '" placeholder="' + escapeHtml(defPlaceholder) + '">';
	}

	function parseOptionsToArray(optsStr) {
		var out = [];
		var lines = (optsStr || '').split('\n');
		for (var i = 0; i < lines.length; i++) {
			var line = lines[i].trim();
			if (!line) continue;
			var val = line, lbl = line;
			if (line.indexOf('|') >= 0) {
				var p = line.split('|', 2);
				val = p[0].trim();
				lbl = (p[1] || p[0]).trim();
			} else if (line.indexOf(':') >= 0) {
				var p2 = line.split(':', 2);
				val = p2[0].trim();
				lbl = (p2[1] || p2[0]).trim();
			}
			out.push({ value: val, label: lbl });
		}
		return out;
	}

	function serializeOptionsArray(arr) {
		if (!arr || !arr.length) return '';
		return arr.map(function(o) {
			var v = (o.value || '').trim();
			var l = (o.label || v).trim();
			return v === l ? v : v + ':' + l;
		}).join('\n');
	}

	function getFieldHtml(fieldData) {
		if (window.wppsOpbGetFieldHtml) {
			return window.wppsOpbGetFieldHtml(fieldData);
		}
		return '';
	}

	function collectFields() {
		if (window.wppsOpbCollectFields) {
			return window.wppsOpbCollectFields();
		}
		return [];
	}

	function validateFieldIds(fields) {
		var seen = {};
		for (var i = 0; i < fields.length; i++) {
			var field = fields[i];
			if (!field || field.type === 'group' || field.type === 'message') continue;
			var id = (field.field_id || '').trim();
			if (!id) continue;
			if (seen[id]) {
				return 'Duplicate field ID "' + id + '". Each field must have a unique ID.';
			}
			seen[id] = true;
		}
		return null;
	}

	function savePage(isAutoSave) {
		isAutoSave = !!isAutoSave;
		var pageId = $('#opb-page-id').val();
		if (!isAutoSave) {
			if (!$('#opb-page-title').val() || !$('#opb-menu-title').val() || !$('#opb-menu-slug').val()) {
				showToast((config.strings && config.strings.required) || 'Page title, menu title, and slug are required.', 'error');
				return;
			}
		}

		var fields = collectFields();
		var duplicateError = validateFieldIds(fields);
		if (duplicateError) {
			updateSaveIndicator('error', duplicateError);
			if (!isAutoSave) showToast(duplicateError, 'error');
			return;
		}

		var data = {
			action: 'wpps_opb_save_page',
			nonce: config.nonce || $('#opb-nonce').val(),
			page_id: pageId,
			page_title: $('#opb-page-title').val(),
			menu_title: $('#opb-menu-title').val(),
			menu_slug: $('#opb-menu-slug').val(),
			page_description: $('#opb-page-description').val(),
			parent_slug: $('#opb-parent-menu').val(),
			capability: $('#opb-capability').val(),
			icon: $('#opb-icon').val(),
			position: $('#opb-position').val(),
			autoload: $('#opb-autoload').is(':checked') ? 1 : 0,
			save_button: $('#opb-save-button').val(),
			updated_message: $('#opb-updated-message').val(),
			fields: JSON.stringify(fields)
		};

		var saveLabel = (config.strings && config.strings.saveLabel) || 'Save Options Page';
		if (!isAutoSave) {
			$('.opb-save-page').prop('disabled', true).text('Saving...');
		}
		updateSaveIndicator('saving');

		$.post(config.ajaxUrl || ajaxurl, data)
			.done(function(r) {
				if (r.success) {
					updateSaveIndicator('saved');
					if (!pageId && r.data && r.data.page_id) {
						window.location.href = 'admin.php?page=powersuite-options-page-builder&action=edit&page_id=' + r.data.page_id;
					} else {
						if (!isAutoSave) {
							showToast((config.strings && config.strings.saved) || 'Saved successfully.', 'success');
							$('.opb-save-page').prop('disabled', false).text(saveLabel);
						}
						setTimeout(function() { updateSaveIndicator(''); }, 3000);
					}
				} else {
					updateSaveIndicator('error', r.data && r.data.message ? r.data.message : (config.strings && config.strings.error) || 'Error');
					showToast(r.data && r.data.message ? r.data.message : (config.strings && config.strings.error) || 'Error', 'error');
					$('.opb-save-page').prop('disabled', false).text(saveLabel);
				}
			})
			.fail(function() {
				updateSaveIndicator('error', (config.strings && config.strings.error) || 'Error');
				showToast((config.strings && config.strings.error) || 'Error', 'error');
				$('.opb-save-page').prop('disabled', false).text(saveLabel);
			});
	}

	function deletePage() {
		if (!confirm((config.strings && config.strings.confirm) || 'Are you sure you want to delete this page? This cannot be undone.')) return;
		var pageId = $('#opb-page-id').val();
		if (!pageId) return;

		$.post(config.ajaxUrl || ajaxurl, {
			action: 'wpps_opb_delete_page',
			nonce: config.nonce || $('#opb-nonce').val(),
			page_id: pageId
		}).done(function(r) {
			if (r.success) {
				showToast('Page deleted.', 'success');
				setTimeout(function() { window.location.href = 'admin.php?page=powersuite-options-page-builder'; }, 800);
			} else {
				showToast(r.data && r.data.message ? r.data.message : 'Error', 'error');
			}
		});
	}

	function addField(type, fieldData) {
		fieldData = fieldData || {};
		fieldData.type = type;
		fieldData.field_id = fieldData.field_id || fieldData.id || generateRandomFieldId();
		fieldData.label = fieldData.label || (type === 'group' ? 'New Section' : (fieldLabels[type] || 'Field'));

		$('#opb-fields-list .wpps-opb-empty-fields').remove();
		$('#opb-fields-list').append(getFieldHtml(fieldData));

		if ($('#opb-fields-list').sortable('instance')) {
			$('#opb-fields-list').sortable('refresh');
		}

		if (window.wppsOpbRefreshConditionalFieldOptions) {
			window.wppsOpbRefreshConditionalFieldOptions();
		}
	}

	function autoSave() {
		if (!currentPageId) return;
		clearTimeout(saveTimeout);
		saveTimeout = setTimeout(function() { savePage(true); }, 1200);
	}

	function initIconPicker() {
		var $btn = $('#opb-icon-picker-btn');
		var $input = $('#opb-icon');
		if (!$btn.length || !$input.length) return;

		var icons = getDashiconsList();
		var searchPlaceholder = (config.strings && config.strings.searchIcons) || 'Search icons…';
		var noMatchText = (config.strings && config.strings.noIconsMatch) || 'No icons match your search.';
		var $wrap = $btn.closest('.wpps-opb-icon-picker-wrap');
		var $dropdown = $(
			'<div class="wpps-opb-icon-picker-dropdown">' +
				'<div class="wpps-opb-icon-picker-search-wrap">' +
					'<input type="search" class="wpps-opb-icon-picker-search wpps-opb-input" placeholder="' + escapeHtml(searchPlaceholder) + '" autocomplete="off" aria-label="' + escapeHtml(searchPlaceholder) + '">' +
				'</div>' +
				'<div class="wpps-opb-icon-picker-grid"></div>' +
				'<p class="wpps-opb-icon-picker-empty" hidden>' + escapeHtml(noMatchText) + '</p>' +
			'</div>'
		);
		var $grid = $dropdown.find('.wpps-opb-icon-picker-grid');
		var gridHtml = icons.map(function(icon) {
			return '<button type="button" class="wpps-opb-icon-picker-item" data-icon="' + escapeHtml(icon) + '" title="' + escapeHtml(icon) + '"><span class="dashicons ' + escapeHtml(icon) + '"></span></button>';
		}).join('');
		$grid.html(gridHtml);
		$wrap.append($dropdown);

		var $search = $dropdown.find('.wpps-opb-icon-picker-search');
		var $empty = $dropdown.find('.wpps-opb-icon-picker-empty');

		function syncSelectedState() {
			var current = ($input.val() || '').trim();
			$grid.find('.wpps-opb-icon-picker-item').removeClass('is-selected').each(function() {
				if ($(this).data('icon') === current) {
					$(this).addClass('is-selected');
				}
			});
		}

		function filterIcons(query) {
			query = (query || '').toLowerCase().replace(/^dashicons-/, '');
			var visible = 0;
			$grid.find('.wpps-opb-icon-picker-item').each(function() {
				var icon = String($(this).data('icon') || '').toLowerCase();
				var match = !query || icon.indexOf(query) !== -1;
				$(this).toggle(match);
				if (match) visible++;
			});
			$empty.prop('hidden', visible > 0);
		}

		$btn.on('click', function(e) {
			e.preventDefault();
			var isOpen = $dropdown.toggleClass('is-open').hasClass('is-open');
			if (isOpen) {
				$search.val('');
				filterIcons('');
				syncSelectedState();
				setTimeout(function() { $search.trigger('focus'); }, 0);
			}
		});

		$search.on('input', function() {
			filterIcons($(this).val());
		});

		$search.on('keydown', function(e) {
			e.stopPropagation();
		});

		$dropdown.on('click', '.wpps-opb-icon-picker-item', function(e) {
			e.preventDefault();
			var icon = $(this).data('icon');
			$input.val(icon).trigger('change');
			$btn.find('.dashicons').attr('class', 'dashicons ' + icon);
			$dropdown.removeClass('is-open');
			syncSelectedState();
			if (currentPageId) autoSave();
		});

		$(document).on('click', function(e) {
			if (!$(e.target).closest('.wpps-opb-icon-picker-wrap').length) {
				$dropdown.removeClass('is-open');
			}
		});

		$input.on('input change', function() {
			var icon = $(this).val() || 'dashicons-admin-generic';
			$btn.find('.dashicons').attr('class', 'dashicons ' + icon);
			syncSelectedState();
		});

		syncSelectedState();
	}

	$(document).ready(function() {
		var urlParams = new URLSearchParams(window.location.search);
		currentPageId = urlParams.get('page_id');

		$('#opb-fields-list').sortable({
			handle: '.wpps-opb-field-drag',
			placeholder: 'wpps-opb-field-placeholder',
			axis: 'y',
			update: function() {
				if (currentPageId) autoSave();
			}
		});

		if (window.wppsOpbInitFieldBuilderExtras) {
			window.wppsOpbInitFieldBuilderExtras({
				escapeHtml: escapeHtml,
				generateRandomFieldId: generateRandomFieldId,
				fieldLabels: fieldLabels,
				fieldTypeIcons: fieldTypeIcons,
				widthLabels: widthLabels,
				defaultPlaceholders: defaultPlaceholders,
				getDefaultInputHtml: getDefaultInputHtml,
				parseOptionsToArray: parseOptionsToArray,
				config: config,
				autoSave: autoSave,
				currentPageId: function() { return currentPageId; }
			});
		}

		if (window.wppsOpbPageData && window.wppsOpbPageData.fields && window.wppsOpbPageData.fields.length) {
			$('#opb-fields-list .wpps-opb-empty-fields').remove();
			window.wppsOpbPageData.fields.forEach(function(f) {
				addField(f.type || 'text', f);
			});
		}

		$('.opb-add-field').on('click', function() {
			addField($(this).data('type'));
		});

		$(document).on('click', '.opb-field-delete', function(e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).closest('.wpps-opb-field-item').remove();
			if ($('#opb-fields-list .wpps-opb-field-item').length === 0) {
				$('#opb-fields-list').html('<div class="wpps-opb-empty-fields">No fields yet. Use Quick Add to create fields.</div>');
			}
			if (window.wppsOpbRefreshConditionalFieldOptions) {
				window.wppsOpbRefreshConditionalFieldOptions();
			}
			if (currentPageId) autoSave();
		});

		$(document).on('click', '.wpps-opb-field-toggle', function(e) {
			e.preventDefault();
			e.stopPropagation();
			$(this).closest('.wpps-opb-field-item').toggleClass('collapsed');
		});

		$(document).on('click', '.wpps-opb-field-header', function(e) {
			if (!$(e.target).closest('.wpps-opb-field-drag, .wpps-opb-field-actions, .opb-field-delete, .opb-field-duplicate').length) {
				$(this).closest('.wpps-opb-field-item').toggleClass('collapsed');
			}
		});

		function syncOptionsEditor($field) {
			var $list = $field.find('.wpps-opb-options-list');
			var $ta = $field.find('.opb-field-options');
			var $defSelect = $field.find('.opb-field-default-select');
			if (!$list.length || !$ta.length) return;
			var arr = [];
			$list.find('.wpps-opb-option-row').each(function() {
				var v = $(this).find('.opb-opt-value').val();
				var l = $(this).find('.opb-opt-label').val();
				if ((v || '').trim()) arr.push({ value: (v || '').trim(), label: (l || v || '').trim() });
			});
			$ta.val(serializeOptionsArray(arr));
			if ($defSelect.length) {
				var curVal = $defSelect.val();
				var hasCur = arr.some(function(o) { return o.value === curVal; });
				if (!hasCur) curVal = '';
				var opts = '<option value="">— None —</option>' + arr.map(function(o) {
					return '<option value="' + escapeHtml(o.value) + '"' + (curVal === o.value ? ' selected' : '') + '>' + escapeHtml(o.label || o.value) + '</option>';
				}).join('');
				$defSelect.html(opts);
				$list.find('.opb-opt-set-default').each(function() {
					var v = $(this).closest('.wpps-opb-option-row').find('.opb-opt-value').val();
					$(this).text(($.trim(v) && curVal === $.trim(v)) ? '✓ Default' : 'Set default');
				});
			}
		}

		$(document).on('click', '.opb-opt-add', function(e) {
			e.preventDefault();
			var $field = $(this).closest('.wpps-opb-field-item');
			var $list = $field.find('.wpps-opb-options-list');
			var $row = $('<div class="wpps-opb-option-row"><input type="text" class="opb-opt-value wpps-opb-input" placeholder="Value"><input type="text" class="opb-opt-label wpps-opb-input" placeholder="Label"><button type="button" class="opb-opt-set-default button button-small" title="Set as default">Set default</button><button type="button" class="opb-opt-remove button button-small" title="Remove">×</button></div>');
			$list.append($row);
			syncOptionsEditor($field);
			if (currentPageId) autoSave();
		});

		$(document).on('click', '.opb-opt-set-default', function(e) {
			e.preventDefault();
			var $field = $(this).closest('.wpps-opb-field-item');
			var val = $(this).closest('.wpps-opb-option-row').find('.opb-opt-value').val();
			if ($.trim(val)) {
				$field.find('.opb-field-default-select').val($.trim(val));
				$field.find('.opb-opt-set-default').text('Set default');
				$(this).text('✓ Default');
				if (currentPageId) autoSave();
			}
		});

		$(document).on('click', '.opb-opt-remove', function(e) {
			e.preventDefault();
			var $field = $(this).closest('.wpps-opb-field-item');
			$(this).closest('.wpps-opb-option-row').remove();
			syncOptionsEditor($field);
			if (currentPageId) autoSave();
		});

		$(document).on('input change', '.opb-opt-value, .opb-opt-label', function() {
			var $field = $(this).closest('.wpps-opb-field-item');
			syncOptionsEditor($field);
			if (currentPageId) autoSave();
		});

		$(document).on('change', '#opb-fields-list .opb-field-default-select', function() {
			var $f = $(this).closest('.wpps-opb-field-item');
			var curVal = $(this).val();
			$f.find('.opb-opt-set-default').each(function() {
				var v = $(this).closest('.wpps-opb-option-row').find('.opb-opt-value').val();
				$(this).text(($.trim(v) && curVal === $.trim(v)) ? '✓ Default' : 'Set default');
			});
			if (currentPageId) autoSave();
		});

		$(document).on('input', '#opb-fields-list .opb-field-default-color', function() {
			var $wrap = $(this).closest('.opb-field-default-color-wrap');
			var hex = $(this).val();
			$wrap.find('.opb-field-default').val(hex);
			if ($(this).closest('.wpps-opb-field-item').length && currentPageId) autoSave();
		});
		$(document).on('input change', '#opb-fields-list .opb-field-default-color-wrap .opb-field-default', function() {
			var $wrap = $(this).closest('.opb-field-default-color-wrap');
			var val = $(this).val().trim().replace(/^#/, '');
			if (/^[0-9a-fA-F]{6}$/.test(val)) {
				$wrap.find('.opb-field-default-color').val('#' + val);
			} else if (/^[0-9a-fA-F]{3}$/.test(val)) {
				$wrap.find('.opb-field-default-color').val('#' + val[0] + val[0] + val[1] + val[1] + val[2] + val[2]);
			}
		});

		$(document).on('change keyup input', '#opb-fields-list .opb-field-label, #opb-fields-list .opb-field-id, #opb-fields-list .opb-field-desc, #opb-fields-list .opb-field-default, #opb-fields-list .opb-field-options, #opb-fields-list .opb-field-required, #opb-fields-list .opb-field-width, #opb-fields-list .opb-field-rows, #opb-fields-list .opb-field-min, #opb-fields-list .opb-field-max, #opb-fields-list .opb-field-checkbox-label, #opb-fields-list .opb-field-radio-layout', function() {
			var $f = $(this).closest('.wpps-opb-field-item');
			var label = $f.find('.opb-field-label').val();
			var width = $f.find('.opb-field-width').val();
			if ($f.find('.opb-field-label').length) $f.find('.wpps-opb-field-title').text(label);
			$f.find('.wpps-opb-field-width-badge').remove();
			if (width && width !== 'full' && $f.find('.opb-field-width').length) {
				$f.find('.wpps-opb-field-type').after('<span class="wpps-opb-field-width-badge">' + (widthLabels[width] || width) + '</span>');
			}
			if (currentPageId) autoSave();
		});

		$(document).on('click', '.opb-save-page', function(e) {
			e.preventDefault();
			savePage(false);
		});

		$(document).on('click', '.opb-delete-page', function(e) {
			e.preventDefault();
			deletePage();
		});

		function getOpbNonce() {
			var $wrap = $('.wpps-opb-page');
			return ($wrap.length && $wrap.attr('data-opb-nonce')) || (config.nonce || '') || ($('#opb-nonce').length ? $('#opb-nonce').val() : '');
		}
		function getOpbAjaxUrl() {
			return (config.ajaxUrl || '') || (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
		}

		$('#wpps-opb-export-btn').on('click', function() {
			var url = getOpbAjaxUrl();
			if (!url) { showToast('AJAX URL not available.', 'error'); return; }
			$.post(url, { action: 'wpps_opb_export_pages', nonce: getOpbNonce() })
				.done(function(r) {
					if (r.success && r.data && r.data.data) {
						var blob = new Blob([r.data.data], { type: 'application/json' });
						var a = document.createElement('a');
						a.href = URL.createObjectURL(blob);
						a.download = 'wp-powersuite-opb-export-' + new Date().toISOString().slice(0,10) + '.json';
						a.click();
						URL.revokeObjectURL(a.href);
						showToast('Export downloaded.', 'success');
					} else {
						showToast(r.data && r.data.message ? r.data.message : 'Export failed', 'error');
					}
				}).fail(function() { showToast('Export failed', 'error'); });
		});

		$(document).on('click', '.wpps-opb-page-export', function(e) {
			e.preventDefault();
			e.stopPropagation();
			var pageId = $(this).data('page-id');
			if (!pageId) return;
			var url = getOpbAjaxUrl();
			if (!url) { showToast('AJAX URL not available.', 'error'); return; }
			$.post(url, { action: 'wpps_opb_export_page', nonce: getOpbNonce(), page_id: pageId })
				.done(function(r) {
					if (r.success && r.data && r.data.data) {
						var blob = new Blob([r.data.data], { type: 'application/json' });
						var a = document.createElement('a');
						a.href = URL.createObjectURL(blob);
						a.download = (r.data.filename || 'opb-page') + '.json';
						a.click();
						URL.revokeObjectURL(a.href);
						showToast('Page exported.', 'success');
					} else {
						showToast(r.data && r.data.message ? r.data.message : 'Export failed', 'error');
					}
				}).fail(function() { showToast('Export failed', 'error'); });
		});

		$('#wpps-opb-import-btn').on('click', function() {
			$('#wpps-opb-import-modal').attr('aria-hidden', 'false').addClass('active').show();
			$('body').css('overflow', 'hidden');
		});
		$('#wpps-opb-import-modal .wpps-modal-close, #wpps-opb-import-cancel').on('click', closeImportModal);
		$('#wpps-opb-import-modal').on('click', function(e) {
			if (e.target === this) {
				closeImportModal();
			}
		});
		$(document).on('keydown', function(e) {
			if (e.key === 'Escape' && $('#wpps-opb-import-modal').hasClass('active')) {
				closeImportModal();
			}
		});
		$('#wpps-opb-import-submit').on('click', function() {
			var json = $('#wpps-opb-import-json').val();
			var replace = $('#wpps-opb-import-replace').is(':checked');
			var url = getOpbAjaxUrl();
			if (!url) { showToast('AJAX URL not available.', 'error'); return; }
			$.post(url, { action: 'wpps_opb_import_pages', nonce: getOpbNonce(), json: json, replace: replace ? 1 : 0 })
				.done(function(r) {
					if (r.success) {
						showToast(r.data && r.data.message ? r.data.message : 'Import successful', 'success');
						closeImportModal();
						window.location.reload();
					} else {
						showToast(r.data && r.data.message ? r.data.message : 'Import failed', 'error');
					}
				}).fail(function() { showToast('Import failed', 'error'); });
		});

		$(document).on('click', '.wpps-opb-page-delete', function(e) {
			e.preventDefault();
			e.stopPropagation();
			var pageId = $(this).data('page-id');
			if (!pageId) return;
			if (!confirm((config.strings && config.strings.confirm) || 'Are you sure you want to delete this page? This cannot be undone.')) return;
			var $card = $(this).closest('.wpps-opb-page-item');
			$.post(config.ajaxUrl || ajaxurl, {
				action: 'wpps_opb_delete_page',
				nonce: config.nonce || $('#opb-nonce').val(),
				page_id: pageId
			}).done(function(r) {
				if (r.success) {
					showToast('Page deleted.', 'success');
					$card.fadeOut(200, function() {
						$(this).remove();
						if ($('.wpps-opb-page-item').length === 0) {
							window.location.reload();
						}
					});
				} else {
					showToast(r.data && r.data.message ? r.data.message : 'Error', 'error');
				}
			}).fail(function() {
				showToast((config.strings && config.strings.error) || 'Error', 'error');
			});
		});

		$('#opb-page-title').on('input', function() {
			var v = $(this).val();
			if (!$('#opb-menu-title').val()) $('#opb-menu-title').val(v);
			if (!$('#opb-menu-slug').prop('readonly')) {
				$('#opb-menu-slug').val(v.toLowerCase().replace(/[^a-z0-9\s-]/g, '').replace(/\s+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, ''));
			}
		});

		$('#opb-parent-menu').on('change', function() {
			var isTop = $(this).val() === '';
			$('#opb-icon-row, #opb-icon-cell, #opb-position-row').toggle(isTop);
		}).trigger('change');

		$('#opb-page-title, #opb-menu-title, #opb-menu-slug, #opb-page-description, #opb-parent-menu, #opb-capability, #opb-icon, #opb-position, #opb-save-button, #opb-updated-message, #opb-autoload').on('change', function() {
			if (currentPageId) autoSave();
		});

		initIconPicker();
	});

})(jQuery);
