/**
 * EasySite VE extras – tour, undo/redo, AI, globals, menu, templates, toasts
 */
(function ($) {
	'use strict';

	var history = [], historyIndex = -1, maxHistory = 30;
	var isRestoring = false;
	var snapTimer = null;

	function snapshot() {
		if (isRestoring || typeof easysiteVE === 'undefined' || !window.esbVEApi) return;
		var state = JSON.stringify({ layout: window.esbVEApi.getLayout(), regions: window.esbVEApi.getRegions() });
		if (historyIndex < history.length - 1) {
			history = history.slice(0, historyIndex + 1);
		}
		if (history.length && history[history.length - 1] === state) return;
		history.push(state);
		if (history.length > maxHistory) history.shift();
		historyIndex = history.length - 1;
		updateUndoButtons();
	}

	function restoreSnapshot(json) {
		if (!window.esbVEApi) return;
		isRestoring = true;
		var data = JSON.parse(json);
		window.esbVEApi.applySnapshot(data, function () {
			window.esbVEApi.markDirty();
			updateUndoButtons();
			toast(easysiteVE.i18n.undone || 'Change restored', 'info');
			setTimeout(function () { isRestoring = false; }, 700);
		}, true);
	}

	function updateUndoButtons() {
		$('#esb-ve-undo').prop('disabled', historyIndex <= 0);
		$('#esb-ve-redo').prop('disabled', historyIndex >= history.length - 1);
	}

	function toast(msg, type) {
		var $t = $('<div class="esb-ve-toast esb-ve-toast--' + (type || 'info') + '">' + msg + '</div>');
		$('body').append($t);
		setTimeout(function () { $t.addClass('is-visible'); }, 10);
		setTimeout(function () { $t.removeClass('is-visible'); setTimeout(function () { $t.remove(); }, 300); }, 3000);
	}

	function runTour() {
		if (!easysiteVE.showTour) return;
		var steps = [
			{ sel: '[contenteditable="true"]', text: easysiteVE.i18n.tourText || 'Click any text to edit it directly on the page.' },
			{ sel: '.esb-editable-image, .esb-ve-change-bg', text: easysiteVE.i18n.tourImage || 'Click images to change them from your media library.' },
			{ sel: '#esb-ve-edit-header', text: easysiteVE.i18n.tourHeader || 'Edit your header, logo, and menu here.' },
			{ sel: '#esb-ve-save', text: easysiteVE.i18n.tourSave || 'Click Save when you are done editing.' }
		];
		var i = 0;
		var $overlay = $('<div id="esb-ve-tour" class="esb-ve-tour"><div class="esb-ve-tour__box"><p></p><button type="button" class="esb-ve-btn esb-ve-btn--primary esb-ve-tour-next">Next</button><button type="button" class="esb-ve-btn esb-ve-tour-skip">Skip</button></div></div>');
		$('body').append($overlay);

		function showStep() {
			if (i >= steps.length) {
				$overlay.remove();
				$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_dismiss_tour', nonce: easysiteVE.nonce });
				return;
			}
			$overlay.find('p').text(steps[i].text);
			var $el = $(steps[i].sel).first();
			if ($el.length) {
				$('html, body').animate({ scrollTop: $el.offset().top - 100 }, 300);
			}
			i++;
		}
		$overlay.on('click', '.esb-ve-tour-next', showStep);
		$overlay.on('click', '.esb-ve-tour-skip', function () {
			$overlay.remove();
			$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_dismiss_tour', nonce: easysiteVE.nonce });
		});
		showStep();
	}

	function injectToolbarExtras() {
		if ($('#esb-ve-undo').length) return;
		var $group = $('<div class="esb-ve-history">' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-undo" title="Undo" disabled><span class="dashicons dashicons-undo"></span></button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-redo" title="Redo" disabled><span class="dashicons dashicons-redo"></span></button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-revisions-btn" title="History">' +
			'<span class="dashicons dashicons-backup"></span></button>' +
			'</div>');
		$('.esb-ve-responsive').before($group);

		$('#esb-ve-add-section').after(
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-page-template">' +
			'<span class="dashicons dashicons-layout"></span> ' + (easysiteVE.i18n.pageTemplate || 'Page template') + '</button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-seo-btn">' +
			'<span class="dashicons dashicons-search"></span> ' + (easysiteVE.i18n.pageSeo || 'Page SEO') + '</button>' +
			(easysiteVE.canExport ? '<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-export-page"><span class="dashicons dashicons-download"></span> ' + (easysiteVE.i18n.exportPage || 'Export') + '</button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-import-page"><span class="dashicons dashicons-upload"></span> ' + (easysiteVE.i18n.importPage || 'Import') + '</button>' : '') +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-forms-btn">' +
			'<span class="dashicons dashicons-feedback"></span> ' + (easysiteVE.i18n.formLabels || 'Form labels') + '</button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-colors-btn">' +
			'<span class="dashicons dashicons-art"></span> ' + (easysiteVE.i18n.brandColors || 'Brand colors') + '</button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-bulk-alt">' +
			'<span class="dashicons dashicons-format-image"></span> ' + (easysiteVE.i18n.bulkAlt || 'Alt text all images') + '</button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-menu-btn">' +
			'<span class="dashicons dashicons-menu"></span> ' + (easysiteVE.i18n.editMenu || 'Menu') + '</button>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-ve-popup-btn">' +
			'<span class="dashicons dashicons-megaphone"></span> ' + (easysiteVE.i18n.editPopup || 'Popup') + '</button>'
		);

		$('body').append(
			'<div id="esb-ve-menu-panel" class="esb-ve-panel" hidden><div class="esb-ve-panel__head"><h3>' + (easysiteVE.i18n.editMenu || 'Menu') + '</h3><button type="button" class="esb-ve-panel__close" data-close-panel>&times;</button></div><div class="esb-ve-panel__body" id="esb-ve-menu-list"></div></div>' +
			'<div id="esb-ve-popup-panel" class="esb-ve-panel" hidden><div class="esb-ve-panel__head"><h3>' + (easysiteVE.i18n.editPopup || 'Popup') + '</h3><button type="button" class="esb-ve-panel__close" data-close-panel>&times;</button></div><div class="esb-ve-panel__body" id="esb-ve-popup-fields"></div></div>' +
			'<div id="esb-ve-template-panel" class="esb-ve-panel" hidden><div class="esb-ve-panel__head"><h3>' + (easysiteVE.i18n.pageTemplate || 'Page template') + '</h3><button type="button" class="esb-ve-panel__close" data-close-panel>&times;</button></div><div class="esb-ve-panel__body" id="esb-ve-template-list"></div></div>' +
			'<div id="esb-ve-revisions-panel" class="esb-ve-panel" hidden><div class="esb-ve-panel__head"><h3>' + (easysiteVE.i18n.pageHistory || 'Page history') + '</h3><button type="button" class="esb-ve-panel__close" data-close-panel>&times;</button></div><div class="esb-ve-panel__body" id="esb-ve-revisions-list"><p class="description">' + (easysiteVE.i18n.historyHelp || 'Restore a previously saved version of this page.') + '</p></div></div>' +
			'<div id="esb-ve-seo-panel" class="esb-ve-panel" hidden><div class="esb-ve-panel__head"><h3>' + (easysiteVE.i18n.pageSeo || 'Page SEO') + '</h3><button type="button" class="esb-ve-panel__close" data-close-panel>&times;</button></div><div class="esb-ve-panel__body" id="esb-ve-seo-fields"></div></div>' +
			'<div id="esb-ve-forms-panel" class="esb-ve-panel" hidden><div class="esb-ve-panel__head"><h3>' + (easysiteVE.i18n.formLabels || 'Form labels') + '</h3><button type="button" class="esb-ve-panel__close" data-close-panel>&times;</button></div><div class="esb-ve-panel__body" id="esb-ve-forms-fields"></div></div>' +
			'<div id="esb-ve-colors-panel" class="esb-ve-panel" hidden><div class="esb-ve-panel__head"><h3>' + (easysiteVE.i18n.brandColors || 'Brand colors') + '</h3><button type="button" class="esb-ve-panel__close" data-close-panel>&times;</button></div><div class="esb-ve-panel__body" id="esb-ve-colors-fields"></div></div>' +
			'<input type="file" id="esb-ve-import-file" accept=".json,application/json" hidden />'
		);
	}

	function bindExtras() {
		$(document).on('click', '#esb-ve-undo', function () {
			if (historyIndex > 0) { historyIndex--; restoreSnapshot(history[historyIndex]); }
		});
		$(document).on('click', '#esb-ve-redo', function () {
			if (historyIndex < history.length - 1) { historyIndex++; restoreSnapshot(history[historyIndex]); }
		});

		$(document).on('esbVEStateChanged', function () {
			if (isRestoring) return;
			clearTimeout(snapTimer);
			snapTimer = setTimeout(function () {
				if (!isRestoring) snapshot();
			}, 500);
		});

		$(document).on('esbVEBlocksWrapped', function () {
			enhanceBlockToolbars();
			addAiButtons();
		});

		$(document).on('click', '.esb-ve-ai-write', function () {
			runAiSuggest($(this), 'general');
		});

		$(document).on('click', '.esb-ve-ai-tone', function (e) {
			e.preventDefault();
			runAiSuggest($(this), $(this).data('tone'));
		});

		$('#esb-ve-menu-btn').on('click', loadMenuPanel);
		$('#esb-ve-popup-btn').on('click', loadPopupPanel);
		$('#esb-ve-page-template').on('click', loadTemplatePanel);
		$('#esb-ve-revisions-btn').on('click', loadRevisionsPanel);
		$('#esb-ve-seo-btn').on('click', loadSeoPanel);
		$('#esb-ve-forms-btn').on('click', loadFormsPanel);
		$('#esb-ve-colors-btn').on('click', loadColorsPanel);
		$('#esb-ve-bulk-alt').on('click', bulkSuggestAlt);
		$('#esb-ve-export-page').on('click', exportPage);
		$('#esb-ve-import-page').on('click', function () { $('#esb-ve-import-file').trigger('click'); });
		$('#esb-ve-import-file').on('change', importPage);

		$(document).on('click', '[data-action="save-global"]', function () {
			var id = $(this).data('block-id');
			var block = getBlock(id);
			if (!block) return;
			var label = prompt(easysiteVE.i18n.globalName || 'Name this section:', block.type);
			if (!label) return;
			$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_save_global_section', nonce: easysiteVE.nonce, label: label, block: JSON.stringify(block) })
				.done(function () { toast(easysiteVE.i18n.globalSaved || 'Section saved to library!', 'success'); });
		});

		$(document).on('click', '[data-action="copy-design"]', function () {
			var id = $(this).data('block-id');
			window.esbVECopiedDesign = (getBlock(id) || {}).design;
			toast(easysiteVE.i18n.designCopied || 'Design copied. Paste on another section.', 'info');
		});

		$(document).on('click', '[data-action="paste-design"]', function () {
			if (!window.esbVECopiedDesign || !window.esbVEApi) return;
			var id = $(this).data('block-id');
			var block = getBlock(id);
			if (block) {
				block.design = JSON.parse(JSON.stringify(window.esbVECopiedDesign));
				window.esbVEApi.applyBlockDesign(id);
				window.esbVEApi.markDirty();
				toast(easysiteVE.i18n.designPasted || 'Design applied!', 'success');
			}
		});

		$(document).on('click', '.esb-ve-restore-revision', function () {
			var index = $(this).data('index');
			if (!confirm(easysiteVE.i18n.restoreConfirm || 'Restore this saved version? Unsaved changes will be lost.')) return;
			$.post(easysiteVE.ajaxUrl, {
				action: 'easysite_ve_restore_revision',
				nonce: easysiteVE.nonce,
				post_id: window.esbVEApi.postId(),
				index: index
			}).done(function (res) {
				if (!res.success || !window.esbVEApi) return;
				isRestoring = true;
				window.esbVEApi.applySnapshot({ layout: res.data.layout, regions: window.esbVEApi.getRegions() }, function () {
					window.esbVEApi.markDirty();
					snapshot();
					$('#esb-ve-revisions-panel').attr('hidden', true);
					toast(easysiteVE.i18n.revisionRestored || 'Version restored!', 'success');
					setTimeout(function () { isRestoring = false; }, 700);
				}, true);
			});
		});

		$(document).ajaxSuccess(function (e, xhr, settings) {
			if (settings.data && settings.data.indexOf('easysite_ve_save_layout') !== -1) {
				try {
					var res = JSON.parse(xhr.responseText);
					if (res.success) {
						toast(easysiteVE.i18n.saved || 'All changes saved!', 'success');
						snapshot();
					}
				} catch (err) { /* ignore */ }
			}
		});

		$(document).on('keydown', function (e) {
			if (!(e.ctrlKey || e.metaKey) && e.key !== 'Escape') return;
			if ((e.ctrlKey || e.metaKey) && e.key === 's') {
				e.preventDefault();
				$('#esb-ve-save').trigger('click');
			}
			if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
				e.preventDefault();
				$('#esb-ve-undo').trigger('click');
			}
			if (e.key === 'Escape') {
				$('.esb-ve-panel:not([hidden])').attr('hidden', true);
			}
		});
	}

	function runAiSuggest($btn, type) {
		var $field = $btn.closest('.esb-ve-field-wrap').find('[data-esb-field], [data-esb-type="richtext"]').first();
		if (!$field.length) $field = $btn.siblings('[contenteditable]');
		$btn.prop('disabled', true);
		$.post(easysiteVE.ajaxUrl, {
			action: 'easysite_ve_ai_suggest',
			nonce: easysiteVE.nonce,
			suggest_type: type,
			context: $field.text() || $field.html()
		}).done(function (res) {
			if (res.success) {
				if ($field.data('esb-type') === 'richtext') $field.html(res.data.text);
				else $field.text(res.data.text);
				$field.trigger('input');
				toast(easysiteVE.i18n.aiDone || 'Text updated!', 'success');
			}
		}).always(function () { $btn.prop('disabled', false); });
	}

	function getBlock(id) {
		if (window.esbVEApi) return (window.esbVEApi.getLayout() || []).find(function (b) { return b.id === id; });
		return null;
	}

	function appendGlobalSections() {
		var globals = easysiteVE.globalSections || [];
		var $grid = $('#esb-ve-library-grid');
		if (!globals.length || !$grid.length) return;
		$grid.find('.esb-ve-library-heading, .esb-ve-global-item').remove();
		$grid.prepend('<p class="esb-ve-library-heading">' + (easysiteVE.i18n.savedSections || 'Saved sections') + '</p>');
		globals.forEach(function (g, i) {
			$grid.prepend('<button type="button" class="esb-ve-library-item esb-ve-global-item" data-global-index="' + i + '"><span class="dashicons dashicons-star-filled"></span><strong>' + (g.label || 'Section') + '</strong></button>');
		});
	}

	$(document).on('click', '.esb-ve-global-item', function (e) {
		e.preventDefault();
		e.stopPropagation();
		var g = (easysiteVE.globalSections || [])[$(this).data('global-index')];
		if (!g || !g.block || !window.esbVEApi) return;
		window.esbVEApi.insertBlock(g.block);
		$('#esb-ve-library').attr('hidden', true);
		toast(easysiteVE.i18n.sectionAdded || 'Section added!', 'success');
	});

	$(document).on('click', '[data-close-panel]', function () {
		$(this).closest('.esb-ve-panel').attr('hidden', true);
	});

	function loadMenuPanel() {
		$('#esb-ve-menu-panel').removeAttr('hidden');
		$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_get_menu', nonce: easysiteVE.nonce }).done(function (res) {
			if (!res.success) return;
			var $list = $('#esb-ve-menu-list').empty();
			$.each(res.data.items, function (_, item) {
				$list.append('<div class="esb-ve-field-row"><label>Link</label><input type="text" class="esb-ve-input esb-ve-menu-title" data-id="' + item.id + '" value="' + $('<div>').text(item.title).html() + '" /><input type="url" class="esb-ve-input esb-ve-menu-url" data-id="' + item.id + '" value="' + item.url + '" /></div>');
			});
		});
	}

	$(document).on('change', '.esb-ve-menu-title, .esb-ve-menu-url', function () {
		var id = $(this).data('id');
		var $row = $(this).closest('.esb-ve-field-row');
		$.post(easysiteVE.ajaxUrl, {
			action: 'easysite_ve_update_menu_item',
			nonce: easysiteVE.nonce,
			item_id: id,
			title: $row.find('.esb-ve-menu-title').val(),
			url: $row.find('.esb-ve-menu-url').val()
		});
		toast(easysiteVE.i18n.menuSaved || 'Menu updated', 'success');
	});

	function loadPopupPanel() {
		$('#esb-ve-popup-panel').removeAttr('hidden');
		var p = easysiteVE.popup || {};
		$('#esb-ve-popup-fields').html(
			'<label><input type="checkbox" id="esb-popup-enabled" ' + (p.enabled ? 'checked' : '') + ' /> Enable popup</label>' +
			'<div class="esb-ve-field-row"><label>Title</label><input type="text" class="esb-ve-input" id="esb-popup-title" value="' + $('<div>').text(p.title || '').html() + '" /></div>' +
			'<div class="esb-ve-field-row"><label>Text</label><textarea class="esb-ve-input" id="esb-popup-text">' + $('<div>').text(p.text || '').html() + '</textarea></div>' +
			'<div class="esb-ve-field-row"><label>Button</label><input type="text" class="esb-ve-input" id="esb-popup-btn" value="' + $('<div>').text(p.button || '').html() + '" /></div>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--primary" id="esb-popup-save">Save popup</button>'
		);
	}

	$(document).on('click', '#esb-popup-save', function () {
		$.post(easysiteVE.ajaxUrl, {
			action: 'easysite_ve_save_popup',
			nonce: easysiteVE.nonce,
			easysite_popup_enabled: $('#esb-popup-enabled').is(':checked') ? 1 : 0,
			easysite_popup_title: $('#esb-popup-title').val(),
			easysite_popup_text: $('#esb-popup-text').val(),
			easysite_popup_button_text: $('#esb-popup-btn').val()
		}).done(function () { toast(easysiteVE.i18n.saved || 'Saved!', 'success'); });
	});

	function loadTemplatePanel() {
		$('#esb-ve-template-panel').removeAttr('hidden');
		var $list = $('#esb-ve-template-list').empty();
		$.each(easysiteVE.pageTemplates || {}, function (key, tpl) {
			$list.append('<button type="button" class="esb-ve-library-item esb-ve-apply-template" data-key="' + key + '"><strong>' + tpl.label + '</strong></button>');
		});
	}

	$(document).on('click', '.esb-ve-apply-template', function () {
		if (!confirm(easysiteVE.i18n.templateConfirm || 'Replace current page content with this template?')) return;
		var key = $(this).data('key');
		var tpl = easysiteVE.pageTemplates[key];
		if (!tpl || !tpl.layout || !window.esbVEApi) return;
		window.esbVEApi.saveLayout(tpl.layout, null, function (res) {
			if (res.success) location.reload();
			else toast(easysiteVE.i18n.error || 'Error', 'error');
		});
	});

	function loadSeoPanel() {
		$('#esb-ve-seo-panel').removeAttr('hidden');
		var seo = easysiteVE.seo || {};
		$('#esb-ve-seo-fields').html(
			'<div class="esb-ve-field-row"><label>' + (easysiteVE.i18n.seoTitle || 'SEO title') + '</label><input type="text" class="esb-ve-input" id="esb-seo-title" value="' + $('<div>').text(seo.title || '').html() + '" /></div>' +
			'<div class="esb-ve-field-row"><label>' + (easysiteVE.i18n.seoDescription || 'Meta description') + '</label><textarea class="esb-ve-input" id="esb-seo-desc" rows="3">' + $('<div>').text(seo.description || '').html() + '</textarea></div>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-seo-suggest-title">' + (easysiteVE.i18n.suggestTitle || 'Suggest title') + '</button> ' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--ghost" id="esb-seo-suggest">' + (easysiteVE.i18n.suggestMeta || 'Suggest description') + '</button> ' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--primary" id="esb-seo-save">' + (easysiteVE.i18n.save || 'Save') + '</button>'
		);
	}

	$(document).on('click', '#esb-seo-suggest-title', function () {
		var hero = $('[data-esb-field="title"]').first().text() || '';
		$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_ai_suggest', nonce: easysiteVE.nonce, suggest_type: 'seo_title', context: hero })
			.done(function (res) { if (res.success) $('#esb-seo-title').val(res.data.text); });
	});

	function loadFormsPanel() {
		$('#esb-ve-forms-panel').removeAttr('hidden');
		var r = (window.esbVEApi && window.esbVEApi.getRegions()) || easysiteVE.regionMods || {};
		$('#esb-ve-forms-fields').html(
			'<div class="esb-ve-field-row"><label>Name</label><input type="text" class="esb-ve-input" id="esb-form-name" value="' + $('<div>').text(r.form_label_name || '').html() + '" /></div>' +
			'<div class="esb-ve-field-row"><label>Email</label><input type="text" class="esb-ve-input" id="esb-form-email" value="' + $('<div>').text(r.form_label_email || '').html() + '" /></div>' +
			'<div class="esb-ve-field-row"><label>Message</label><input type="text" class="esb-ve-input" id="esb-form-message" value="' + $('<div>').text(r.form_label_message || '').html() + '" /></div>' +
			'<div class="esb-ve-field-row"><label>Submit</label><input type="text" class="esb-ve-input" id="esb-form-submit" value="' + $('<div>').text(r.form_label_submit || '').html() + '" /></div>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--primary" id="esb-form-save">' + (easysiteVE.i18n.save || 'Save') + '</button>'
		);
	}

	$(document).on('click', '#esb-form-save', function () {
		if (!window.esbVEApi) return;
		var regions = window.esbVEApi.getRegions();
		regions.form_label_name = $('#esb-form-name').val();
		regions.form_label_email = $('#esb-form-email').val();
		regions.form_label_message = $('#esb-form-message').val();
		regions.form_label_submit = $('#esb-form-submit').val();
		window.esbVEApi.setRegions(regions);
		$('[data-esb-region-field="form_label_name"]').text(regions.form_label_name);
		$('[data-esb-region-field="form_label_email"]').text(regions.form_label_email);
		$('[data-esb-region-field="form_label_message"]').text(regions.form_label_message);
		$('[data-esb-region-field="form_label_submit"]').text(regions.form_label_submit);
		window.esbVEApi.markDirty();
		toast(easysiteVE.i18n.saved || 'Saved!', 'success');
	});

	function loadColorsPanel() {
		$('#esb-ve-colors-panel').removeAttr('hidden');
		var c = easysiteVE.brandColors || {};
		$('#esb-ve-colors-fields').html(
			'<div class="esb-ve-field-row"><label>Main color</label><input type="color" class="esb-ve-input" id="esb-color-main" value="' + (c.main || '#2563eb') + '" /></div>' +
			'<div class="esb-ve-field-row"><label>Accent color</label><input type="color" class="esb-ve-input" id="esb-color-accent" value="' + (c.accent || '#7c3aed') + '" /></div>' +
			'<button type="button" class="esb-ve-btn esb-ve-btn--primary" id="esb-colors-save">' + (easysiteVE.i18n.save || 'Save') + '</button>'
		);
	}

	$(document).on('click', '#esb-colors-save', function () {
		$.post(easysiteVE.ajaxUrl, {
			action: 'easysite_ve_save_brand_colors', nonce: easysiteVE.nonce,
			main_color: $('#esb-color-main').val(), accent_color: $('#esb-color-accent').val()
		}).done(function () {
			toast(easysiteVE.i18n.saved || 'Saved!', 'success');
			location.reload();
		});
	});

	function bulkSuggestAlt() {
		var $imgs = $('.esb-editable-image img');
		if (!$imgs.length) return;
		var i = 0;
		function next() {
			if (i >= $imgs.length) { toast(easysiteVE.i18n.aiDone || 'Done!', 'success'); return; }
			var $img = $imgs.eq(i++);
			$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_ai_suggest', nonce: easysiteVE.nonce, suggest_type: 'alt', context: $img.attr('alt') || '' })
				.done(function (res) { if (res.success) $img.attr('alt', res.data.text); next(); });
		}
		next();
	}

	$(document).on('click', '#esb-seo-suggest', function () {
		$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_ai_suggest', nonce: easysiteVE.nonce, suggest_type: 'meta', context: $('#esb-seo-desc').val() })
			.done(function (res) { if (res.success) $('#esb-seo-desc').val(res.data.text); });
	});

	$(document).on('click', '#esb-seo-save', function () {
		$.post(easysiteVE.ajaxUrl, {
			action: 'easysite_ve_save_seo', nonce: easysiteVE.nonce, post_id: window.esbVEApi.postId(),
			seo_title: $('#esb-seo-title').val(), seo_description: $('#esb-seo-desc').val()
		}).done(function () { toast(easysiteVE.i18n.saved || 'Saved!', 'success'); });
	});

	function exportPage() {
		$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_export_page', nonce: easysiteVE.nonce, post_id: window.esbVEApi.postId() })
			.done(function (res) {
				if (!res.success) return;
				var blob = new Blob([JSON.stringify(res.data)], { type: 'application/json' });
				var a = document.createElement('a');
				a.href = URL.createObjectURL(blob);
				a.download = 'easysite-page.json';
				a.click();
			});
	}

	function importPage() {
		var file = this.files[0];
		if (!file || !window.esbVEApi) return;
		var reader = new FileReader();
		reader.onload = function (e) {
			if (!confirm(easysiteVE.i18n.templateConfirm || 'Replace current page content?')) return;
			$.post(easysiteVE.ajaxUrl, {
				action: 'easysite_ve_import_page', nonce: easysiteVE.nonce,
				post_id: window.esbVEApi.postId(), kit: e.target.result
			}).done(function (res) {
				if (res.success) location.reload();
			});
		};
		reader.readAsText(file);
		$('#esb-ve-import-file').val('');
	}

	function loadRevisionsPanel() {
		$('#esb-ve-revisions-panel').removeAttr('hidden');
		var $list = $('#esb-ve-revisions-list');
		$list.find('.esb-ve-revision-item, .esb-ve-no-revisions').remove();
		$.post(easysiteVE.ajaxUrl, {
			action: 'easysite_ve_get_revisions',
			nonce: easysiteVE.nonce,
			post_id: window.esbVEApi.postId()
		}).done(function (res) {
			if (!res.success || !res.data.revisions.length) {
				$list.append('<p class="esb-ve-no-revisions">' + (easysiteVE.i18n.noHistory || 'No saved versions yet. Save the page to create history.') + '</p>');
				return;
			}
			$list.find('.esb-ve-no-revisions').remove();
			$.each(res.data.revisions, function (i, rev) {
				var date = new Date(rev.time * 1000);
				var label = date.toLocaleString();
				var sections = (rev.layout || []).length;
				$list.append(
					'<div class="esb-ve-revision-item">' +
					'<div><strong>' + label + '</strong><br><span class="description">' + sections + ' ' + (easysiteVE.i18n.sections || 'sections') + '</span></div>' +
					'<button type="button" class="esb-ve-btn esb-ve-btn--ghost esb-ve-restore-revision" data-index="' + i + '">' + (easysiteVE.i18n.restore || 'Restore') + '</button>' +
					'</div>'
				);
			});
		});
	}

	function enhanceBlockToolbars() {
		$('.esb-ve-block-actions').each(function () {
			var $actions = $(this);
			if ($actions.find('[data-action="save-global"]').length) return;
			var id = $actions.closest('.easysite-pb-block').data('block-id');
			$actions.prepend(
				'<button type="button" class="esb-ve-icon-btn" data-action="copy-design" data-block-id="' + id + '" title="Copy design"><span class="dashicons dashicons-admin-appearance"></span></button>' +
				'<button type="button" class="esb-ve-icon-btn" data-action="paste-design" data-block-id="' + id + '" title="Paste design"><span class="dashicons dashicons-clipboard"></span></button>' +
				'<button type="button" class="esb-ve-icon-btn" data-action="save-global" data-block-id="' + id + '" title="Save section"><span class="dashicons dashicons-star-filled"></span></button>'
			);
		});
	}

	function addAiButtons() {
		$('[data-esb-type="text"], [data-esb-type="richtext"]').each(function () {
			var $el = $(this);
			if ($el.closest('.esb-ve-field-wrap').length) return;
			$el.wrap('<div class="esb-ve-field-wrap"></div>');
			var $wrap = $el.closest('.esb-ve-field-wrap');
			$wrap.append('<div class="esb-ve-ai-group">' +
				'<button type="button" class="esb-ve-ai-write">' + (easysiteVE.i18n.aiWrite || 'Write for me') + '</button>' +
				'<button type="button" class="esb-ve-ai-tone" data-tone="shorter">' + (easysiteVE.i18n.shorter || 'Shorter') + '</button>' +
				'<button type="button" class="esb-ve-ai-tone" data-tone="friendlier">' + (easysiteVE.i18n.friendlier || 'Friendlier') + '</button>' +
				'<button type="button" class="esb-ve-ai-tone" data-tone="professional">' + (easysiteVE.i18n.professional || 'Professional') + '</button>' +
				'</div>');
		});
		$('.esb-editable-image').each(function () {
			var $img = $(this);
			if ($img.find('.esb-ve-suggest-alt').length) return;
			$img.append('<button type="button" class="esb-ve-suggest-alt">' + (easysiteVE.i18n.altText || 'Suggest alt text') + '</button>');
		});
	}

	$(document).on('click', '.esb-ve-suggest-alt', function (e) {
		e.preventDefault();
		e.stopPropagation();
		var $img = $(this).closest('.esb-editable-image').find('img');
		var ctx = $img.attr('alt') || '';
		$.post(easysiteVE.ajaxUrl, { action: 'easysite_ve_ai_suggest', nonce: easysiteVE.nonce, suggest_type: 'alt', context: ctx })
			.done(function (res) {
				if (res.success) { $img.attr('alt', res.data.text); toast(easysiteVE.i18n.aiDone || 'Updated!', 'success'); }
			});
	});

	$(function () {
		if (typeof easysiteVE === 'undefined') return;
		injectToolbarExtras();
		bindExtras();
		// Wait for esbVEApi from visual-editor.js
		var ready = setInterval(function () {
			if (!window.esbVEApi) return;
			clearInterval(ready);
			snapshot();
			enhanceBlockToolbars();
			addAiButtons();
			appendGlobalSections();
			runTour();
		}, 100);
	});
})(jQuery);
