<?php
$builder_id = !empty($builder_id) ? $builder_id : 'quotation-form-builder';
$hidden_input_id = !empty($hidden_input_id) ? $hidden_input_id : 'quotationforms_code';
$builder_fields = (!empty($builder_fields) && is_array($builder_fields)) ? array_values($builder_fields) : array();
?>

<div id="<?= html_escape($builder_id) ?>" class="qfb rounded-2xl border border-border bg-card shadow-sm">
	<div class="border-b border-border px-5 py-4">
		<div class="flex items-center gap-2 text-sm font-semibold text-foreground">
			<i data-lucide="layout-grid" class="h-5 w-5"></i>
			<h3 class="text-base font-semibold"><?= lang('form_builder') ?></h3>
		</div>
		<p class="mt-1 text-sm text-muted-foreground">Click field buttons to add and build a professional quotation request form.</p>
	</div>

	<div class="grid gap-5 p-5 xl:grid-cols-12">
		<aside class="xl:col-span-4 qfb-sidebar rounded-xl border border-border bg-background">
			<div class="qfb-tabs">
				<button type="button" class="qfb-tab rounded-tl-xl is-active" data-tab-target="add">Add New Field</button>
				<button type="button" class="qfb-tab rounded-tl-xl" data-tab-target="edit">Edit Field</button>
			</div>

			<div class="qfb-panel p-4" data-tab-panel="add">
				<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2">
					<button type="button" class="qfb-add-btn" data-add-type="text"><i data-lucide="type" class="h-4 w-4"></i><span>Text</span></button>
					<button type="button" class="qfb-add-btn" data-add-type="paragraph"><i data-lucide="pilcrow" class="h-4 w-4"></i><span>Paragraph</span></button>
					<button type="button" class="qfb-add-btn" data-add-type="checkboxes"><i data-lucide="check-square" class="h-4 w-4"></i><span>Checkboxes</span></button>
					<button type="button" class="qfb-add-btn" data-add-type="radio"><i data-lucide="circle-dot" class="h-4 w-4"></i><span>Multiple Choice</span></button>
					<button type="button" class="qfb-add-btn sm:col-span-2 xl:col-span-1 2xl:col-span-2" data-add-type="dropdown"><i data-lucide="chevron-down-square" class="h-4 w-4"></i><span>Dropdown</span></button>
				</div>
				<div class="mt-4 rounded-lg border border-dashed border-border bg-muted/20 p-3 text-xs text-muted-foreground">
					Tip: Select a field on the right to edit label, description, required state, and options.
				</div>
			</div>

			<div class="qfb-panel hidden p-4" data-tab-panel="edit">
				<div data-edit-panel class="rounded-lg border border-border bg-muted/10 p-4 text-sm text-muted-foreground">
					Select a field to edit its settings.
				</div>
			</div>
		</aside>

		<section class="xl:col-span-8">
			<div class="qfb-stage rounded-xl border border-border bg-background p-4" data-stage></div>
		</section>
	</div>
</div>

<style>
	#<?= $builder_id ?> .qfb-tabs {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		border-bottom: 1px solid hsl(var(--border));
	}

	#<?= $builder_id ?> .qfb-tab {
		border: 0;
		background: hsl(var(--background));
		color: hsl(var(--muted-foreground));
		font-size: 13px;
		font-weight: 700;
		padding: 12px 14px;
		text-align: center;
		transition: all .15s ease;
	}

	#<?= $builder_id ?> .qfb-tab.is-active {
		background: hsl(var(--primary) / .12);
		color: hsl(var(--primary));
		box-shadow: inset 0 -2px 0 hsl(var(--primary));
	}

	#<?= $builder_id ?> .qfb-add-btn {
		display: inline-flex;
		align-items: center;
		justify-content: flex-start;
		gap: 10px;
		border: 1px solid hsl(var(--border));
		background: hsl(var(--card));
		color: hsl(var(--foreground));
		font-size: 14px;
		font-weight: 600;
		border-radius: 10px;
		padding: 11px 12px;
		transition: all .15s ease;
	}

	#<?= $builder_id ?> .qfb-add-btn:hover {
		background: hsl(var(--primary) / .10);
		border-color: hsl(var(--primary) / .45);
		color: hsl(var(--primary));
	}

	#<?= $builder_id ?> .qfb-stage-empty {
		min-height: 420px;
		border: 2px dashed hsl(var(--border));
		border-radius: 14px;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		padding: 24px;
		color: hsl(var(--muted-foreground));
		font-size: 14px;
		background: linear-gradient(180deg, hsl(var(--muted) / .15), hsl(var(--background)));
	}

	#<?= $builder_id ?> .qfb-field-card {
		border: 1px solid hsl(var(--border));
		border-radius: 14px;
		background: hsl(var(--card));
		padding: 12px;
		margin-bottom: 12px;
		box-shadow: 0 14px 28px -24px rgba(2, 6, 23, .55);
		transition: all .15s ease;
		cursor: pointer;
	}

	#<?= $builder_id ?> .qfb-field-card.is-active {
		border-color: hsl(var(--primary) / .55);
		box-shadow: 0 0 0 1px hsl(var(--primary) / .25), 0 14px 28px -24px rgba(2, 6, 23, .55);
	}

	#<?= $builder_id ?> .qfb-card-head {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 8px;
		margin-bottom: 10px;
	}

	#<?= $builder_id ?> .qfb-type-chip {
		display: inline-flex;
		align-items: center;
		gap: 6px;
		border: 1px solid hsl(var(--border));
		background: hsl(var(--muted) / .25);
		color: hsl(var(--muted-foreground));
		border-radius: 999px;
		padding: 3px 10px;
		font-size: 11px;
		font-weight: 700;
		letter-spacing: .04em;
		text-transform: uppercase;
	}

	#<?= $builder_id ?> .qfb-size-chip {
		display: inline-flex;
		align-items: center;
		border: 1px solid hsl(var(--border));
		background: hsl(var(--background));
		color: hsl(var(--muted-foreground));
		border-radius: 999px;
		padding: 3px 8px;
		font-size: 10px;
		font-weight: 700;
		letter-spacing: .04em;
		text-transform: uppercase;
	}

	#<?= $builder_id ?> .qfb-card-actions {
		display: inline-flex;
		align-items: center;
		gap: 6px;
	}

	#<?= $builder_id ?> .qfb-icon-btn {
		width: 28px;
		height: 28px;
		border: 1px solid hsl(var(--border));
		border-radius: 8px;
		background: hsl(var(--background));
		color: hsl(var(--muted-foreground));
		font-size: 12px;
		display: inline-flex;
		align-items: center;
		justify-content: center;
	}

	#<?= $builder_id ?> .qfb-icon-btn:hover {
		background: hsl(var(--muted) / .4);
		color: hsl(var(--foreground));
	}

	#<?= $builder_id ?> .qfb-icon-btn.qfb-danger:hover {
		background: hsl(var(--destructive) / .14);
		color: hsl(var(--destructive));
		border-color: hsl(var(--destructive) / .45);
	}

	#<?= $builder_id ?> .qfb-preview {
		border: 1px solid hsl(var(--border));
		border-radius: 10px;
		background: hsl(var(--background));
		padding: 10px;
	}

	#<?= $builder_id ?> .qfb-label {
		display: block;
		font-size: 13px;
		font-weight: 700;
		color: hsl(var(--foreground));
		margin-bottom: 7px;
	}

	#<?= $builder_id ?> .qfb-label .qfb-required {
		color: hsl(var(--destructive));
		margin-left: 3px;
	}

	#<?= $builder_id ?> .qfb-desc {
		font-size: 12px;
		color: hsl(var(--muted-foreground));
		margin: -2px 0 8px;
	}

	#<?= $builder_id ?> .qfb-input,
	#<?= $builder_id ?> .qfb-textarea,
	#<?= $builder_id ?> .qfb-select {
		width: 100%;
		border: 1px solid hsl(var(--border));
		border-radius: 9px;
		padding: 9px 10px;
		font-size: 13px;
		background: hsl(var(--input));
		color: hsl(var(--foreground));
		outline: none;
		transition: border-color .18s ease, box-shadow .18s ease, background-color .18s ease;
		box-shadow: inset 0 1px 2px hsl(var(--foreground) / .04);
	}

	#<?= $builder_id ?> .qfb-input::placeholder,
	#<?= $builder_id ?> .qfb-textarea::placeholder {
		color: hsl(var(--muted-foreground));
		opacity: .92;
	}

	#<?= $builder_id ?> .qfb-input:hover,
	#<?= $builder_id ?> .qfb-textarea:hover,
	#<?= $builder_id ?> .qfb-select:hover {
		border-color: hsl(var(--primary) / .38);
	}

	#<?= $builder_id ?> .qfb-input:focus,
	#<?= $builder_id ?> .qfb-textarea:focus,
	#<?= $builder_id ?> .qfb-select:focus {
		border-color: hsl(var(--primary) / .78);
		background: hsl(var(--background));
		box-shadow: 0 0 0 3px hsl(var(--primary) / .16), inset 0 1px 2px hsl(var(--foreground) / .05);
	}

	#<?= $builder_id ?> .qfb-input:focus-visible,
	#<?= $builder_id ?> .qfb-textarea:focus-visible,
	#<?= $builder_id ?> .qfb-select:focus-visible {
		outline: none;
	}

	#<?= $builder_id ?> .qfb-textarea {
		resize: vertical;
	}

	#<?= $builder_id ?> .qfb-option-row {
		display: grid;
		grid-template-columns: auto minmax(0, 1fr) auto;
		gap: 8px;
		align-items: center;
		margin-bottom: 8px;
	}

	#<?= $builder_id ?> .qfb-option-row:last-child {
		margin-bottom: 0;
	}

	#<?= $builder_id ?> .qfb-option-bullet {
		width: 16px;
		text-align: center;
		color: hsl(var(--muted-foreground));
	}

	#<?= $builder_id ?> .qfb-add-option {
		margin-top: 8px;
		border: 1px dashed hsl(var(--border));
		border-radius: 9px;
		background: hsl(var(--background));
		color: hsl(var(--foreground));
		font-size: 12px;
		font-weight: 600;
		padding: 8px 10px;
	}
</style>

<script>
	(function() {
		var root = document.getElementById(<?= json_encode($builder_id) ?>);
		if (!root) return;

		var hiddenInput = document.getElementById(<?= json_encode($hidden_input_id) ?>);
		if (!hiddenInput) return;

		var stage = root.querySelector('[data-stage]');
		var editPanel = root.querySelector('[data-edit-panel]');
		var tabs = root.querySelectorAll('[data-tab-target]');
		var panels = root.querySelectorAll('[data-tab-panel]');

		var initialFields = <?= json_encode($builder_fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;

		var TYPE_META = {
			text: {
				label: 'Text',
				icon: 'type'
			},
			paragraph: {
				label: 'Paragraph',
				icon: 'pilcrow'
			},
			checkboxes: {
				label: 'Checkboxes',
				icon: 'check-square'
			},
			radio: {
				label: 'Multiple Choice',
				icon: 'circle-dot'
			},
			dropdown: {
				label: 'Dropdown',
				icon: 'chevron-down-square'
			}
		};

		function uid() {
			return 'qf_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
		}

		function esc(value) {
			return String(value || '').replace(/[&<>"']/g, function(ch) {
				return ({
					'&': '&amp;',
					'<': '&lt;',
					'>': '&gt;',
					'"': '&quot;',
					"'": '&#39;'
				})[ch];
			});
		}

		function optionDefaults(type) {
			if (type === 'checkboxes') {
				return [{
					label: 'Option 1',
					checked: 0
				}, {
					label: 'Option 2',
					checked: 0
				}];
			}
			if (type === 'radio' || type === 'dropdown') {
				return [{
					label: 'Option 1',
					checked: 1
				}, {
					label: 'Option 2',
					checked: 0
				}];
			}
			return [];
		}

		function createField(type) {
			var fieldType = TYPE_META[type] ? type : 'text';
			var base = {
				_id: uid(),
				cid: 'c' + uid(),
				field_type: fieldType,
				label: TYPE_META[fieldType].label,
				required: 1,
				field_options: {
					description: '',
					column: 12
				}
			};
			if (fieldType === 'paragraph') {
				base.field_options.size = 'medium';
			}
			if (fieldType === 'checkboxes' || fieldType === 'radio' || fieldType === 'dropdown') {
				base.field_options.options = optionDefaults(fieldType);
			}
			return base;
		}

		function normalizeFields(rawFields) {
			if (!Array.isArray(rawFields)) return [];
			var out = [];
			for (var i = 0; i < rawFields.length; i++) {
				var raw = rawFields[i];
				if (!raw || typeof raw !== 'object') continue;
				var type = TYPE_META[raw.field_type] ? raw.field_type : 'text';
				var field = createField(type);
				field.label = raw.label ? String(raw.label) : field.label;
				field.required = Number(raw.required) === 1 ? 1 : 0;
				field.cid = raw.cid ? String(raw.cid) : field.cid;
				var options = raw.field_options && typeof raw.field_options === 'object' ? raw.field_options : {};
				field.field_options.description = options.description ? String(options.description) : '';
				var column = parseInt(options.column, 10);
				field.field_options.column = [12, 6, 4, 3].indexOf(column) !== -1 ? column : 12;
				if (type === 'paragraph') {
					field.field_options.size = (options.size === 'small' || options.size === 'large') ? options.size : 'medium';
				}
				if (type === 'checkboxes' || type === 'radio' || type === 'dropdown') {
					var sourceOptions = Array.isArray(options.options) ? options.options : [];
					var mapped = sourceOptions.map(function(opt, idx) {
						return {
							label: (opt && opt.label) ? String(opt.label) : ('Option ' + (idx + 1)),
							checked: (opt && Number(opt.checked) === 1) ? 1 : 0
						};
					});
					if (!mapped.length) mapped = optionDefaults(type);
					if (type === 'radio' || type === 'dropdown') {
						var hasChecked = mapped.some(function(opt) {
							return opt.checked === 1;
						});
						if (!hasChecked && mapped[0]) mapped[0].checked = 1;
						mapped = mapped.map(function(opt, idx) {
							return {
								label: opt.label,
								checked: idx === mapped.findIndex(function(fopt) {
									return fopt.checked === 1;
								}) ? 1 : 0
							};
						});
					}
					field.field_options.options = mapped;
				}
				out.push(field);
			}
			return out;
		}

		var fields = normalizeFields(initialFields);
		var selectedIndex = fields.length ? 0 : -1;

		function setActiveTab(tabName) {
			for (var i = 0; i < tabs.length; i++) {
				var tab = tabs[i];
				var active = tab.getAttribute('data-tab-target') === tabName;
				tab.classList.toggle('is-active', active);
			}
			for (var j = 0; j < panels.length; j++) {
				var panel = panels[j];
				var show = panel.getAttribute('data-tab-panel') === tabName;
				panel.classList.toggle('hidden', !show);
			}
		}

		function getField(index) {
			if (index < 0 || index >= fields.length) return null;
			return fields[index];
		}

		function serialize() {
			var payloadFields = fields.map(function(field) {
				var copy = {
					cid: field.cid,
					field_type: field.field_type,
					label: field.label,
					required: Number(field.required) === 1 ? 1 : 0,
					field_options: {
						description: (field.field_options && field.field_options.description) ? field.field_options.description : '',
						column: (field.field_options && [12, 6, 4, 3].indexOf(parseInt(field.field_options.column, 10)) !== -1) ? parseInt(field.field_options.column, 10) : 12
					}
				};
				if (field.field_type === 'paragraph') {
					copy.field_options.size = (field.field_options && field.field_options.size) ? field.field_options.size : 'medium';
				}
				if (field.field_type === 'checkboxes' || field.field_type === 'radio' || field.field_type === 'dropdown') {
					var opts = (field.field_options && Array.isArray(field.field_options.options)) ? field.field_options.options : [];
					if (!opts.length) opts = optionDefaults(field.field_type);
					if (field.field_type === 'radio' || field.field_type === 'dropdown') {
						var selected = opts.findIndex(function(opt) {
							return Number(opt.checked) === 1;
						});
						if (selected < 0) selected = 0;
						opts = opts.map(function(opt, idx) {
							return {
								label: opt.label || ('Option ' + (idx + 1)),
								checked: idx === selected ? 1 : 0
							};
						});
					}
					copy.field_options.options = opts.map(function(opt, idx) {
						return {
							label: opt.label || ('Option ' + (idx + 1)),
							checked: Number(opt.checked) === 1 ? 1 : 0
						};
					});
				}
				return copy;
			});
			hiddenInput.value = JSON.stringify({
				fields: payloadFields
			});
		}

		function refreshIcons() {
			if (window.lucide && typeof window.lucide.createIcons === 'function') {
				window.lucide.createIcons();
			}
		}

		function previewMarkup(field) {
			if (field.field_type === 'text') {
				return '<input type="text" class="qfb-input" disabled placeholder="<?= lang('short_answer_text') ?>">';
			}
			if (field.field_type === 'paragraph') {
				var minHeight = '96px';
				if (field.field_options.size === 'small') minHeight = '70px';
				if (field.field_options.size === 'large') minHeight = '150px';
				return '<textarea class="qfb-textarea" style="min-height:' + minHeight + '" disabled placeholder="<?= lang('long_answer_text') ?>"></textarea>';
			}
			if (field.field_type === 'dropdown') {
				var dropdownOptions = (field.field_options.options || []).map(function(opt) {
					return '<option>' + esc(opt.label) + '</option>';
				}).join('');
				return '<select class="qfb-select" disabled>' + dropdownOptions + '</select>';
			}
			if (field.field_type === 'checkboxes') {
				var checkboxOptions = (field.field_options.options || []).map(function(opt) {
					return '<label class="inline-flex items-center gap-2 text-sm mr-4 mb-2"><input type="checkbox" disabled ' + (Number(opt.checked) === 1 ? 'checked' : '') + '><span>' + esc(opt.label) + '</span></label>';
				}).join('');
				return '<div>' + checkboxOptions + '</div>';
			}
			var radioOptions = (field.field_options.options || []).map(function(opt) {
				return '<label class="inline-flex items-center gap-2 text-sm mr-4 mb-2"><input type="radio" disabled ' + (Number(opt.checked) === 1 ? 'checked' : '') + '><span>' + esc(opt.label) + '</span></label>';
			}).join('');
			return '<div>' + radioOptions + '</div>';
		}

		function renderStage() {
			if (!fields.length) {
				stage.innerHTML = '<div class="qfb-stage-empty"><div><p class="font-semibold text-foreground mb-1">No fields yet</p><p>Use the left panel to add Text, Paragraph, Checkboxes, Multiple Choice, or Dropdown.</p></div></div>';
				return;
			}

			stage.innerHTML = fields.map(function(field, index) {
				var meta = TYPE_META[field.field_type] || TYPE_META.text;
				var required = Number(field.required) === 1 ? '<span class="qfb-required">*</span>' : '';
				var desc = (field.field_options && field.field_options.description) ? '<p class="qfb-desc">' + esc(field.field_options.description) + '</p>' : '';
				var col = (field.field_options && [12, 6, 4, 3].indexOf(parseInt(field.field_options.column, 10)) !== -1) ? parseInt(field.field_options.column, 10) : 12;
				return '' +
					'<article class="qfb-field-card ' + (index === selectedIndex ? 'is-active' : '') + '" data-index="' + index + '">' +
					'<div class="qfb-card-head">' +
					'<div class="inline-flex items-center gap-2"><span class="qfb-type-chip"><i data-lucide="' + meta.icon + '" class="h-3.5 w-3.5"></i>' + esc(meta.label) + '</span><span class="qfb-size-chip">col-' + col + '</span></div>' +
					'<div class="qfb-card-actions">' +
					'<button type="button" class="qfb-icon-btn" data-act="up" title="<?= lang('move_up') ?>"><i data-lucide="arrow-up" class="h-3.5 w-3.5"></i></button>' +
					'<button type="button" class="qfb-icon-btn" data-act="down" title="<?= lang('move_down') ?>"><i data-lucide="arrow-down" class="h-3.5 w-3.5"></i></button>' +
					'<button type="button" class="qfb-icon-btn" data-act="duplicate" title="<?= lang('duplicate') ?>"><i data-lucide="copy" class="h-3.5 w-3.5"></i></button>' +
					'<button type="button" class="qfb-icon-btn qfb-danger" data-act="delete" title="<?= lang('delete') ?>"><i data-lucide="trash-2" class="h-3.5 w-3.5"></i></button>' +
					'</div>' +
					'</div>' +
					'<label class="qfb-label">' + esc(field.label) + required + '</label>' +
					desc +
					'<div class="qfb-preview">' + previewMarkup(field) + '</div>' +
					'</article>';
			}).join('');
			refreshIcons();
		}

		function optionRowsMarkup(field) {
			var options = (field.field_options && Array.isArray(field.field_options.options)) ? field.field_options.options : [];
			return options.map(function(opt, idx) {
				var checkedControl = '';
				if (field.field_type === 'checkboxes') {
					checkedControl = '<input type="checkbox" data-opt-check="' + idx + '" ' + (Number(opt.checked) === 1 ? 'checked' : '') + '>';
				} else {
					checkedControl = '<input type="radio" name="qfb_default_opt" data-opt-default="' + idx + '" ' + (Number(opt.checked) === 1 ? 'checked' : '') + '>';
				}
				return '' +
					'<div class="qfb-option-row">' +
					'<span class="qfb-option-bullet">' + checkedControl + '</span>' +
					'<input class="qfb-input" type="text" value="' + esc(opt.label) + '" data-opt-input="' + idx + '">' +
					'<button type="button" class="qfb-icon-btn qfb-danger" data-opt-remove="' + idx + '"><i data-lucide="minus-circle" class="h-3.5 w-3.5"></i></button>' +
					'</div>';
			}).join('');
		}

		function renderEditPanel() {
			var field = getField(selectedIndex);
			if (!field) {
				editPanel.innerHTML = '<div class="text-sm text-muted-foreground">Select a field to edit its settings.</div>';
				return;
			}

			var isOptionType = (field.field_type === 'checkboxes' || field.field_type === 'radio' || field.field_type === 'dropdown');
			var paragraphSize = field.field_options.size || 'medium';
			var columnSize = (field.field_options && [12, 6, 4, 3].indexOf(parseInt(field.field_options.column, 10)) !== -1) ? parseInt(field.field_options.column, 10) : 12;

			editPanel.innerHTML = '' +
				'<div class="space-y-4">' +
				'<div class="rounded-lg border border-border bg-muted/20 px-3 py-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">' +
				'Type: <span class="text-foreground">' + esc((TYPE_META[field.field_type] || TYPE_META.text).label) + '</span>' +
				'</div>' +
				'<div>' +
				'<label class="qfb-label mb-1">Label</label>' +
				'<input type="text" class="qfb-input" data-edit-input="label" value="' + esc(field.label) + '">' +
				'</div>' +
				'<div>' +
				'<label class="qfb-label mb-1">Description</label>' +
				'<textarea class="qfb-textarea" rows="3" data-edit-input="description">' + esc(field.field_options.description || '') + '</textarea>' +
				'</div>' +
				'<div>' +
				'<label class="qfb-label mb-1">Field Width</label>' +
				'<select class="qfb-select" data-edit-input="column">' +
				'<option value="12" ' + (columnSize === 12 ? 'selected' : '') + '>Full width (col-12)</option>' +
				'<option value="6" ' + (columnSize === 6 ? 'selected' : '') + '>Half width (col-6)</option>' +
				'<option value="4" ' + (columnSize === 4 ? 'selected' : '') + '>One-third (col-4)</option>' +
				'<option value="3" ' + (columnSize === 3 ? 'selected' : '') + '>One-quarter (col-3)</option>' +
				'</select>' +
				'</div>' +
				'<label class="inline-flex items-center gap-2 text-sm font-medium text-foreground">' +
				'<input type="checkbox" data-edit-input="required" ' + (Number(field.required) === 1 ? 'checked' : '') + '>' +
				'<span>Required</span>' +
				'</label>' +
				(field.field_type === 'paragraph' ? (
					'<div>' +
					'<label class="qfb-label mb-1">Paragraph Size</label>' +
					'<select class="qfb-select" data-edit-input="size">' +
					'<option value="small" ' + (paragraphSize === 'small' ? 'selected' : '') + '>Small</option>' +
					'<option value="medium" ' + (paragraphSize === 'medium' ? 'selected' : '') + '>Medium</option>' +
					'<option value="large" ' + (paragraphSize === 'large' ? 'selected' : '') + '>Large</option>' +
					'</select>' +
					'</div>'
				) : '') +
				(isOptionType ? (
					'<div>' +
					'<label class="qfb-label mb-1">Options</label>' +
					'<div data-option-list>' + optionRowsMarkup(field) + '</div>' +
					'<button type="button" class="qfb-add-option" data-opt-add><i data-lucide="plus-circle" class="mr-1 h-3.5 w-3.5"></i>Add Option</button>' +
					'</div>'
				) : '') +
				'</div>';
			refreshIcons();
		}

		function rerender() {
			renderStage();
			renderEditPanel();
			serialize();
		}

		root.addEventListener('click', function(e) {
			var tabBtn = e.target.closest('[data-tab-target]');
			if (tabBtn && root.contains(tabBtn)) {
				setActiveTab(tabBtn.getAttribute('data-tab-target'));
				return;
			}

			var addBtn = e.target.closest('[data-add-type]');
			if (addBtn && root.contains(addBtn)) {
				var type = addBtn.getAttribute('data-add-type');
				fields.push(createField(type));
				selectedIndex = fields.length - 1;
				setActiveTab('edit');
				rerender();
				return;
			}

			var actionBtn = e.target.closest('[data-act]');
			if (actionBtn && root.contains(actionBtn)) {
				var card = actionBtn.closest('.qfb-field-card');
				if (!card) return;
				var idx = Number(card.getAttribute('data-index'));
				var act = actionBtn.getAttribute('data-act');
				if (Number.isNaN(idx)) return;

				if (act === 'delete') {
					fields.splice(idx, 1);
					if (selectedIndex >= fields.length) selectedIndex = fields.length - 1;
					if (!fields.length) selectedIndex = -1;
					rerender();
					return;
				}
				if (act === 'duplicate') {
					var source = fields[idx];
					var clone = JSON.parse(JSON.stringify(source));
					clone._id = uid();
					clone.cid = 'c' + uid();
					fields.splice(idx + 1, 0, clone);
					selectedIndex = idx + 1;
					rerender();
					return;
				}
				if (act === 'up' && idx > 0) {
					var tmpUp = fields[idx - 1];
					fields[idx - 1] = fields[idx];
					fields[idx] = tmpUp;
					selectedIndex = idx - 1;
					rerender();
					return;
				}
				if (act === 'down' && idx < fields.length - 1) {
					var tmpDown = fields[idx + 1];
					fields[idx + 1] = fields[idx];
					fields[idx] = tmpDown;
					selectedIndex = idx + 1;
					rerender();
					return;
				}
			}

			var fieldCard = e.target.closest('.qfb-field-card');
			if (fieldCard && root.contains(fieldCard)) {
				selectedIndex = Number(fieldCard.getAttribute('data-index'));
				if (!Number.isNaN(selectedIndex)) {
					setActiveTab('edit');
					rerender();
				}
				return;
			}

			if (e.target.closest('[data-opt-add]') && root.contains(e.target)) {
				var current = getField(selectedIndex);
				if (!current) return;
				if (!Array.isArray(current.field_options.options)) current.field_options.options = [];
				current.field_options.options.push({
					label: 'Option ' + (current.field_options.options.length + 1),
					checked: 0
				});
				rerender();
			}

			var optRemove = e.target.closest('[data-opt-remove]');
			if (optRemove && root.contains(optRemove)) {
				var removeField = getField(selectedIndex);
				if (!removeField || !Array.isArray(removeField.field_options.options)) return;
				var removeIdx = Number(optRemove.getAttribute('data-opt-remove'));
				if (removeField.field_options.options.length <= 1) return;
				if (!Number.isNaN(removeIdx)) {
					removeField.field_options.options.splice(removeIdx, 1);
					if (removeField.field_type === 'radio' || removeField.field_type === 'dropdown') {
						var checkedIndex = removeField.field_options.options.findIndex(function(opt) {
							return Number(opt.checked) === 1;
						});
						if (checkedIndex < 0 && removeField.field_options.options[0]) {
							removeField.field_options.options[0].checked = 1;
						}
					}
					rerender();
				}
			}
		});

		root.addEventListener('input', function(e) {
			var field = getField(selectedIndex);
			if (!field) return;
			var editInput = e.target.getAttribute('data-edit-input');
			if (editInput === 'label') {
				field.label = e.target.value;
				serialize();
				renderStage();
				return;
			}
			if (editInput === 'description') {
				field.field_options.description = e.target.value;
				serialize();
				return;
			}
			if (editInput === 'size') {
				field.field_options.size = e.target.value;
				rerender();
				return;
			}
			var optionInput = e.target.getAttribute('data-opt-input');
			if (optionInput !== null) {
				var optIdx = Number(optionInput);
				if (!Number.isNaN(optIdx) && field.field_options.options && field.field_options.options[optIdx]) {
					field.field_options.options[optIdx].label = e.target.value;
					serialize();
					renderStage();
				}
			}
		});

		root.addEventListener('change', function(e) {
			var field = getField(selectedIndex);
			if (!field) return;
			var editInput = e.target.getAttribute('data-edit-input');
			if (editInput === 'required') {
				field.required = e.target.checked ? 1 : 0;
				rerender();
				return;
			}
			if (editInput === 'column') {
				var col = parseInt(e.target.value, 10);
				field.field_options.column = [12, 6, 4, 3].indexOf(col) !== -1 ? col : 12;
				rerender();
				return;
			}

			var optCheck = e.target.getAttribute('data-opt-check');
			if (optCheck !== null) {
				var checkIdx = Number(optCheck);
				if (!Number.isNaN(checkIdx) && field.field_options.options && field.field_options.options[checkIdx]) {
					field.field_options.options[checkIdx].checked = e.target.checked ? 1 : 0;
					rerender();
				}
				return;
			}

			var optDefault = e.target.getAttribute('data-opt-default');
			if (optDefault !== null) {
				var defaultIdx = Number(optDefault);
				if (!Number.isNaN(defaultIdx) && field.field_options.options) {
					field.field_options.options = field.field_options.options.map(function(opt, idx) {
						return {
							label: opt.label,
							checked: idx === defaultIdx ? 1 : 0
						};
					});
					rerender();
				}
			}
		});

		var form = root.closest('form');
		if (form) {
			form.addEventListener('submit', function() {
				serialize();
			});
		}

		setActiveTab('add');
		rerender();
		refreshIcons();
	})();
</script>
