/**
 * EasySite Visual Page Builder – admin drag-and-drop UI
 */
(function ($) {
	'use strict';

	var $wrap, $canvas, $hidden, $empty, registry, layout;

	function init() {
		$wrap = $('#easysite-page-builder');
		if (!$wrap.length) return;

		registry = $wrap.data('registry') || {};
		layout = $wrap.data('layout') || [];
		$canvas = $('#easysite-pb-canvas');
		$hidden = $('#easysite-builder-layout');
		$empty = $('.easysite-pb-empty');

		renderCanvas();
		bindEvents();
		toggleEmpty();
	}

	function uid() {
		return 'esb_' + Math.random().toString(36).slice(2, 11);
	}

	function bindEvents() {
		$('input[name="easysite_use_builder"]').on('change', function () {
			$('.easysite-pb-ui').toggleClass('is-disabled', !this.checked);
		});

		$wrap.on('click', '.easysite-pb-add-section', function (e) {
			e.preventDefault();
			addSection($(this).data('type'));
		});

		$canvas.sortable({
			handle: '.easysite-pb-block-handle',
			placeholder: 'easysite-pb-placeholder',
			update: syncFromDom
		});

		$wrap.on('click', '.easysite-pb-remove', function (e) {
			e.preventDefault();
			$(this).closest('.easysite-pb-block-admin').remove();
			syncFromDom();
			toggleEmpty();
		});

		$wrap.on('click', '.easysite-pb-toggle-fields', function (e) {
			e.preventDefault();
			$(this).closest('.easysite-pb-block-admin').find('.easysite-pb-fields').slideToggle(200);
		});

		$wrap.on('input change', '.easysite-pb-field-input', syncFromDom);

		$wrap.on('click', '.easysite-pb-pick-image', function (e) {
			e.preventDefault();
			var $btn = $(this);
			var $input = $btn.siblings('input.easysite-pb-field-input');
			var frame = wp.media({
				title: easysitePageBuilder.i18n.selectImg,
				button: { text: easysitePageBuilder.i18n.changeImg },
				multiple: false
			});
			frame.on('select', function () {
				var url = frame.state().get('selection').first().toJSON().url;
				$input.val(url).trigger('change');
				$btn.siblings('.easysite-pb-img-preview').attr('src', url).show();
			});
			frame.open();
		});

		$wrap.on('click', '.easysite-pb-ai-field', function (e) {
			e.preventDefault();
			var $field = $(this).siblings('.easysite-pb-field-input');
			if (window.easysiteAI) {
				window.easysiteAI.suggest('general', $field[0]);
			}
		});
	}

	function addSection(type) {
		if (!registry[type]) return;
		var block = {
			id: uid(),
			type: type,
			fields: {}
		};
		$.each(registry[type].fields, function (key) {
			block.fields[key] = '';
		});
		layout.push(block);
		$canvas.append(renderBlock(block));
		syncFromDom();
		toggleEmpty();
	}

	function renderCanvas() {
		$canvas.empty();
		$.each(layout, function (_, block) {
			$canvas.append(renderBlock(block));
		});
	}

	function renderBlock(block) {
		var def = registry[block.type];
		if (!def) return '';

		var $el = $('<li class="easysite-pb-block-admin" data-id="' + block.id + '" data-type="' + block.type + '">' +
			'<div class="easysite-pb-block-head">' +
			'<span class="easysite-pb-block-handle dashicons dashicons-move" title="Drag"></span>' +
			'<strong><span class="dashicons ' + def.icon + '"></span> ' + def.label + '</strong>' +
			'<span class="easysite-pb-block-actions">' +
			'<button type="button" class="button-link easysite-pb-toggle-fields">' + easysitePageBuilder.i18n.edit + '</button> ' +
			'<button type="button" class="button-link easysite-pb-remove">' + easysitePageBuilder.i18n.remove + '</button>' +
			'</span></div>' +
			'<div class="easysite-pb-fields" style="display:none;"></div></li>');

		var $fields = $el.find('.easysite-pb-fields');
		$.each(def.fields, function (key, field) {
			var val = (block.fields && block.fields[key]) ? block.fields[key] : '';
			var $row = $('<div class="easysite-pb-field-row"></div>');
			$row.append('<label>' + field.label + '</label>');

			if (field.type === 'textarea') {
				$row.append('<textarea class="widefat easysite-pb-field-input" data-key="' + key + '">' + esc(val) + '</textarea>');
				if (easysiteAdmin && easysiteAdmin.bundle) {
					$row.append('<button type="button" class="button easysite-pb-ai-field">' + easysitePageBuilder.i18n.aiSuggest + '</button>');
				}
			} else if (field.type === 'select') {
				var $sel = $('<select class="easysite-pb-field-input" data-key="' + key + '"></select>');
				$.each(field.options, function (ov, ol) {
					$sel.append('<option value="' + ov + '"' + (val === ov ? ' selected' : '') + '>' + ol + '</option>');
				});
				$row.append($sel);
			} else if (field.type === 'image') {
				$row.append('<input type="hidden" class="easysite-pb-field-input" data-key="' + key + '" value="' + esc(val) + '" />');
				$row.append('<img class="easysite-pb-img-preview" src="' + (val || '') + '" ' + (val ? '' : 'style="display:none"') + ' />');
				$row.append('<button type="button" class="button easysite-pb-pick-image">' + easysitePageBuilder.i18n.selectImg + '</button>');
			} else {
				$row.append('<input type="text" class="widefat easysite-pb-field-input" data-key="' + key + '" value="' + esc(val) + '" placeholder="' + (field.placeholder || '') + '" />');
			}
			$fields.append($row);
		});

		return $el;
	}

	function esc(s) {
		return $('<div>').text(s || '').html();
	}

	function syncFromDom() {
		layout = [];
		$canvas.find('.easysite-pb-block-admin').each(function () {
			var $b = $(this);
			var fields = {};
			$b.find('.easysite-pb-field-input').each(function () {
				fields[$(this).data('key')] = $(this).val();
			});
			layout.push({
				id: $b.data('id'),
				type: $b.data('type'),
				fields: fields
			});
		});
		$hidden.val(JSON.stringify(layout));
	}

	function toggleEmpty() {
		var has = $canvas.children().length > 0;
		$empty.toggle(!has);
		$canvas.toggle(has);
	}

	$(init);
})(jQuery);
