<?php
$new_status_html = form_lookup_add_link(
	'lead_status_id',
	base_url('admin/leads/lead_status'),
	lang('create') . ' ' . lang('lead_status')
);

$selected_status_name = !empty($form->lead_status_id) ? $form->lead_status_id : (!empty($lead_status_id) ? $lead_status_id : '');
$selected_status_name_label = null;
if (!empty($form->lead_status_id)) {
	$lead = $this->db->where('lead_status_id', $form->lead_status_id)->get('tbl_lead_status')->row();
	if (!empty($lead)) {
		$selected_status_name_label = $lead->lead_status;
	}
}

$new_source_html = form_lookup_add_link(
	'lead_source_id',
	base_url('admin/leads/lead_source'),
	lang('create') . ' ' . lang('lead_source')
);

$selected_source_name = !empty($form->lead_source_id) ? $form->lead_source_id : (!empty($lead_source_id) ? $lead_source_id : '');
$selected_source_name_label = null;
if (!empty($form->lead_source_id)) {
	$source = $this->db->where('lead_source_id', $form->lead_source_id)->get('tbl_lead_source')->row();
	if (!empty($source)) {
		$selected_source_name_label = $source->lead_source;
	}
}

$language_options = array();
if (!empty($languages)) {
	foreach ($languages as $lang) {
		$language_options[$lang->name] = ucfirst($lang->name);
	}
}

$permissionL = null;
if (!empty($form->permission)) {
	$permissionL = $form->permission;
}

$lead_form_success_message = $this->session->flashdata('success');
$lead_form_error_message = $this->session->flashdata('error');
$lead_form_show_saved_toast = (!empty($lead_form_success_message) && $lead_form_success_message === lang('update_lead_form'));
?>

<div class="space-y-4">
	<?php if (!empty($lead_form_success_message) || !empty($lead_form_error_message)) { ?>
		<script>
			(function() {
				var successMessage = <?= json_encode($lead_form_show_saved_toast ? 'Saved: Builder + Settings' : $lead_form_success_message); ?>;
				var errorMessage = <?= json_encode($lead_form_error_message); ?>;
				var notify = function(type, message) {
					if (!message) return;
					if (window.toaster && typeof window.toaster[type] === 'function') {
						window.toaster[type](message);
						return;
					}
					if (window.toastr && typeof window.toastr[type] === 'function') {
						window.toastr[type](message);
						return;
					}
					alert(message);
				};
				if (document.readyState === 'loading') {
					document.addEventListener('DOMContentLoaded', function() {
						notify('success', successMessage);
						notify('error', errorMessage);
					});
				} else {
					notify('success', successMessage);
					notify('error', errorMessage);
				}
			})();
		</script>
	<?php } ?>

	<div class="overflow-hidden rounded-lg border border-border bg-card">
		<div class="border-b border-border px-5 py-4">
			<div class="flex flex-wrap items-start justify-between gap-4">
				<div>
					<h2 class="text-lg font-semibold text-foreground"><?= lang('lead_form') ?></h2>
					<p class="mt-1 text-sm text-muted-foreground"><?= lang('form_builder') ?> <?= lang('and') ?> <?= lang('form_information') ?></p>
				</div>
				<?php if (isset($form)) { ?>
					<div class="inline-flex items-center rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-muted-foreground">
						<?= lang('form') ?> #<?= $form->lead_form_id ?>
					</div>
				<?php } ?>
			</div>
		</div>

		<div class="space-y-5 p-5">
			<?php if (!isset($form)) { ?>
				<div class="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-300">
					<?= lang('form_builder_create_form_first') ?>
				</div>
			<?php } ?>

			<?= form_open('admin/leads/save_form_data/row', array('id' => 'form_info', 'class' => 'space-y-5')); ?>
			<?php if (isset($form)) {
				echo form_hidden('form_id', $form->lead_form_id);
			} ?>
			<input type="hidden" name="formData" id="lead_form_data" value="">

			<?php if (isset($form)) { ?>
				<ul class="nav nav-tabs lead-form-main-tabs flex w-full gap-2 border-b border-border" role="tablist" data-lead-tabs>
					<li role="presentation" class="active">
						<a href="#tab_form_build" aria-controls="tab_form_build" role="tab" data-toggle="tab"
							class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground">
							<i data-lucide="layout-template" class="h-4 w-4"></i>
							<span><?= lang('form_builder'); ?></span>
						</a>
					</li>
					<li role="presentation">
						<a href="#tab_form_information" aria-controls="tab_form_information" role="tab" data-toggle="tab"
							class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground">
							<i data-lucide="settings-2" class="h-4 w-4"></i>
							<span><?= lang('form_information') ?> &amp; <?= lang('settings') ?></span>
						</a>
					</li>
				</ul>
			<?php } ?>

			<div class="tab-content pt-4 lead-form-tab-content">
				<?php if (isset($form)) { ?>
					<div role="tabpanel" class="tab-pane active" id="tab_form_build">
						<div class="rounded-lg border border-border bg-background p-4">
							<div class="lead-builder-shell">
								<aside class="lead-builder-palette" data-builder-palette>
									<p class="lead-builder-palette-title"><?= lang('available') ?> <?= lang('fields') ?></p>
									<div class="lead-builder-palette-list">
										<button type="button" class="js-builder-palette-item" data-field-type="header" data-field-label="Header">
											<i data-lucide="heading-1"></i><span>Header</span>
										</button>
										<button type="button" class="js-builder-palette-item" data-field-type="paragraph" data-field-label="Paragraph">
											<i data-lucide="pilcrow"></i><span>Paragraph</span>
										</button>
										<button type="button" class="js-builder-palette-item" data-field-type="file" data-field-label="File Upload">
											<i data-lucide="upload"></i><span>File Upload</span>
										</button>
										<?php if (!empty($db_fields)) {
											foreach ($db_fields as $field) { ?>
												<button type="button" class="js-builder-palette-item" data-field-type="<?= html_escape($field->name) ?>" data-field-label="<?= html_escape($field->label) ?>">
													<i data-lucide="minus"></i><span><?= html_escape($field->label) ?></span>
												</button>
										<?php }
										} ?>
									</div>
								</aside>
								<div class="lead-builder-stage">
									<div id="build-wrap" class="lead-form-builder"></div>
								</div>
							</div>
						</div>
					</div>
				<?php } ?>

				<div role="tabpanel" class="tab-pane <?php if (!isset($form)) {
															echo 'active';
														} ?>" id="tab_form_information">
					<div class="grid gap-5 xl:grid-cols-12">
						<div class="space-y-5 xl:col-span-8">
							<?php if (isset($form)) { ?>
								<section class="rounded-lg border border-border bg-background p-5">
									<h3 class="mb-3 text-base font-semibold text-foreground"><?= lang('form') . ' ' . lang('integration') ?></h3>
									<div class="rounded-lg border border-border bg-muted/20 p-4">
										<div class="flex flex-wrap items-center justify-between gap-3">
											<a class="inline-flex items-center rounded-md border border-border bg-background px-3 py-2 text-xs font-medium text-foreground hover:bg-muted"
												href="<?= site_url('forms/leads/' . $form->form_key); ?>" target="_blank">
												<?= site_url('forms/leads/' . $form->form_key); ?>
											</a>
											<span class="text-xs text-muted-foreground"><?= lang('copy') ?> <?= lang('and') ?> <?= lang('use') ?> <?= lang('embed_code') ?></span>
										</div>
										<div class="mt-3">
											<textarea class="w-full rounded-lg border border-border bg-input px-3 py-2 text-sm" id="foo"
												rows="2"><iframe width="600" height="850" src="<?= site_url('forms/leads/' . $form->form_key); ?>" frameborder="0" allowfullscreen></iframe></textarea>
										</div>
									</div>
								</section>
							<?php } ?>

							<section class="rounded-lg border border-border bg-background p-5">
								<h3 class="mb-4 text-base font-semibold text-foreground"><?= lang('general') ?></h3>
								<div class="grid grid-cols-1 gap-5 md:grid-cols-2">
									<?= form_input_group('form_name', lang('form') . ' ' . lang('name'), !empty($form) ? $form->form_name : '', 'text', true); ?>
									<?= form_lookup_group('lead_status_id', lang('lead_status'), $selected_status_name, $selected_status_name_label, true, array(), '', array('type' => 'lead_status', 'append' => $new_status_html)); ?>
									<?= form_select_group(
										'language',
										lang('language'),
										$language_options,
										!empty($form->language) ? $form->language : $this->config->item('language'),
										false,
										array('class' => 'select_box', 'style' => 'width:100%')
									); ?>
									<?= form_lookup_group('lead_source_id', lang('lead_source'), $selected_source_name, $selected_source_name_label, true, array(), '', array('type' => 'lead_source', 'append' => $new_source_html)); ?>
								</div>

								<div class="mt-5 grid grid-cols-1 gap-5 md:grid-cols-2">
									<?= form_input_group('submit_btn_text', lang('submit_btn_text'), !empty($form) ? $form->submit_btn_text : '', 'text', true); ?>
									<?= form_textarea_group('submit_btn_msg', lang('submit_btn_msg'), !empty($form) ? $form->submit_btn_msg : '', 3, false); ?>
								</div>
							</section>

							<section class="rounded-lg border border-border bg-background p-5">
								<h3 class="mb-4 text-base font-semibold text-foreground"><?= lang('settings') ?></h3>

								<?php if (config_item('recaptcha_secret_key') != '' && config_item('recaptcha_site_key') != '') { ?>
									<div class="mb-4 rounded-lg border border-border bg-muted/20 p-4">
										<label class="text-sm font-medium text-foreground block mb-2"><?= lang('form') . ' ' . lang('recaptcha'); ?></label>
										<input data-toggle="toggle" name="form_recaptcha"
											value="1" <?php if (!empty($form) && $form->form_recaptcha == 1) {
														echo 'checked';
													} ?>
											data-on="<?= lang('yes') ?>" data-off="<?= lang('no') ?>"
											data-onstyle="success" data-offstyle="danger" type="checkbox">
									</div>
								<?php } ?>

								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="rounded-lg border border-border bg-muted/20 p-4">
										<label class="inline-flex items-center gap-2 text-sm text-foreground">
											<input name="allow_duplicate" id="showhide" type="checkbox" value="1"
												class="h-4 w-4 rounded border-border text-indigo-600 focus:ring-indigo-500"
												<?php
												if (!empty($form) && $form->allow_duplicate == 1) {
													echo 'checked';
												} elseif (empty($form)) {
													echo 'checked';
												}
												?>>
											<span class="font-medium"><?= lang('allow_duplicate_leads') ?></span>
										</label>
									</div>

									<div id="shresult" class="rounded-lg border border-border bg-muted/20 p-4" style="display: <?php
																																if (!empty($form) && $form->allow_duplicate != 1) {
																																	echo 'block';
																																} else {
																																	echo 'none';
																																} ?>">
										<label class="text-sm font-medium text-foreground mb-2 block"><?= lang('track_duplicate_field') ?></label>
										<select name="track_duplicate_field" class="form-control select_box w-full" style="width:100%">
											<option value=""></option>
											<?php foreach ($db_fields as $field) { ?>
												<option value="<?= $field->name; ?>" <?php if (isset($form) && $form->track_duplicate_field == $field->name) {
																							echo 'selected';
																						} ?>>
													<?= $field->label; ?>
												</option>
											<?php } ?>
										</select>
									</div>

									<div class="rounded-lg border border-border bg-muted/20 p-4 md:col-span-2">
										<label class="inline-flex items-center gap-2 text-sm text-foreground">
											<input name="notify_lead_imported" type="checkbox" value="1"
												class="h-4 w-4 rounded border-border text-indigo-600 focus:ring-indigo-500"
												<?php
												if (!empty($form) && $form->notify_lead_imported == 1) {
													echo 'checked';
												} elseif (empty($form)) {
													echo 'checked';
												}
												?>>
											<span class="font-medium"><?= lang('notify_lead_imported') ?></span>
										</label>
									</div>
								</div>
							</section>
						</div>

						<div class="space-y-5 xl:col-span-4">
							<section class="rounded-lg border border-border bg-background p-5">
								<h3 class="mb-4 text-base font-semibold text-foreground"><?= lang('assigned') ?></h3>
								<?= form_permission_modern($assign_user, $permissionL, lang('assigned_to')); ?>
							</section>
						</div>
					</div>

					<div class="mt-6 flex items-center justify-end gap-2 border-t border-border pt-5">
						<button type="submit" class="inline-flex items-center rounded-lg bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90">
							<?= lang('save') ?>
						</button>
					</div>
				</div>
			</div>
			<?= form_close(); ?>
		</div>
	</div>
</div>

<script src="<?= base_url() ?>assets/plugins/elfinder/jquery-ui.min.js"></script>
<script src="<?= base_url('plugins/formbuilder/form-builder.min.js'); ?>"></script>
<style>
	#tab_form_information,
	#tab_form_build {
		margin-top: 0;
	}

	.lead-form-tab-content>.tab-pane {
		display: none;
	}

	.lead-form-tab-content>.tab-pane.active {
		display: block;
	}

	.lead-form-main-tabs>li {
		float: none;
	}

	.lead-form-main-tabs>li>a {
		border: 0;
		border-bottom: 2px solid transparent;
		background: transparent;
		color: hsl(var(--muted-foreground));
		transition: color 0.15s ease, border-color 0.15s ease;
	}

	.lead-form-main-tabs>li>a:hover {
		color: hsl(var(--foreground));
	}

	.lead-form-main-tabs>li.active>a,
	.lead-form-main-tabs>li.active>a:focus,
	.lead-form-main-tabs>li.active>a:hover {
		background: transparent;
		border-bottom-color: hsl(var(--primary));
		color: hsl(var(--primary));
	}

	#tab_form_build .lead-form-builder .form-wrap.form-builder {
		border: 1px solid hsl(var(--border));
		border-radius: 8px;
		background: hsl(var(--card));
		overflow: hidden;
	}

	.lead-builder-shell {
		display: grid;
		grid-template-columns: 260px minmax(0, 1fr);
		gap: 16px;
	}

	.lead-builder-palette {
		border: 1px solid hsl(var(--border));
		border-radius: 8px;
		background: hsl(var(--card));
		overflow: hidden;
	}

	.lead-builder-palette-title {
		margin: 0;
		padding: 10px 12px;
		font-size: 11px;
		font-weight: 700;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: hsl(var(--muted-foreground));
		border-bottom: 1px solid hsl(var(--border));
		background: hsl(var(--muted));
	}

	.lead-builder-palette-list {
		max-height: 620px;
		overflow-y: auto;
	}

	.lead-builder-palette-list .js-builder-palette-item {
		width: 100%;
		display: flex;
		align-items: center;
		gap: 8px;
		text-align: left;
		padding: 9px 12px;
		border: 0;
		border-bottom: 1px solid hsl(var(--border));
		background: hsl(var(--card));
		color: hsl(var(--foreground));
		font-size: 13px;
		font-weight: 500;
		transition: background-color 0.15s ease, color 0.15s ease;
	}

	.lead-builder-palette-list .js-builder-palette-item i {
		width: 16px;
		text-align: center;
		color: hsl(var(--muted-foreground));
	}

	.lead-builder-palette-list .js-builder-palette-item:hover {
		background: hsl(var(--muted));
		color: hsl(var(--primary));
	}

	.lead-builder-palette-list .js-builder-palette-item:hover i {
		color: hsl(var(--primary));
	}

	.lead-builder-palette-list .js-builder-palette-item:focus-visible {
		outline: 2px solid hsl(var(--primary) / 0.5);
		outline-offset: -2px;
	}

	.lead-builder-stage {
		border: 1px solid hsl(var(--border));
		border-radius: 8px;
		background: hsl(var(--card));
		padding: 12px;
	}

	#tab_form_build .lead-form-builder .cb-wrap {
		display: none !important;
	}

	#tab_form_build .lead-form-builder .cb-wrap h4 {
		font-size: 11px;
		text-transform: uppercase;
		letter-spacing: 0.08em;
		font-weight: 700;
		color: hsl(var(--muted-foreground));
		margin-bottom: 8px;
	}

	#tab_form_build .lead-form-builder .frmb-control li {
		border-radius: 10px;
		border: 1px solid hsl(var(--border));
		background: hsl(var(--background));
		margin-bottom: 8px;
		padding: 10px 12px;
		font-size: 13px;
		font-weight: 600;
		color: hsl(var(--foreground));
		cursor: pointer;
		transition: all 0.15s ease;
	}

	#tab_form_build .lead-form-builder .frmb-control li:hover {
		border-color: hsl(var(--primary) / 0.6);
		background: hsl(var(--primary) / 0.08);
		transform: translateX(2px);
	}

	#tab_form_build .lead-form-builder .frmb-control li.disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	#tab_form_build .lead-form-builder .stage-wrap {
		background: hsl(var(--background));
		padding: 0;
		min-height: 560px;
		display: block !important;
		float: none !important;
		width: 100% !important;
	}

	#tab_form_build .lead-form-builder .form-wrap.form-builder::after {
		content: '';
		display: block;
		clear: both;
	}

	#tab_form_build .lead-form-builder .frmb {
		min-height: 560px;
		border: 1px dashed hsl(var(--border));
		border-radius: 8px;
		padding: 12px;
		background: hsl(var(--background));
	}

	#tab_form_build .lead-form-builder .frmb li.form-field {
		border: 1px solid hsl(var(--border));
		border-radius: 8px;
		background: hsl(var(--card));
		margin-bottom: 10px;
		box-shadow: none;
		overflow: hidden;
	}

	#tab_form_build .lead-form-builder .frmb .field-actions {
		display: flex;
		justify-content: flex-end;
		padding: 8px 8px 0;
	}

	#tab_form_build .lead-form-builder .frmb .del-button {
		border: 1px solid hsl(var(--border));
		background: hsl(var(--background));
		color: hsl(var(--muted-foreground));
		border-radius: 6px;
		width: 28px;
		height: 28px;
		line-height: 1;
		font-size: 16px;
		font-weight: 700;
		padding: 0;
		transition: all 0.15s ease;
	}

	#tab_form_build .lead-form-builder .frmb .del-button:hover {
		background: hsl(var(--destructive) / 0.12);
		border-color: hsl(var(--destructive) / 0.4);
		color: hsl(var(--destructive));
	}

	#tab_form_build .lead-form-builder .frmb .prev-holder {
		padding: 6px 12px 12px;
	}

	#tab_form_build .lead-form-builder .frmb .fbp-block {
		border: 1px solid hsl(var(--border));
		background: hsl(var(--background));
		border-radius: 8px;
		padding: 12px;
	}

	#tab_form_build .lead-form-builder .frmb .fbp-label {
		display: block;
		margin: 0 0 8px;
		font-size: 13px;
		font-weight: 700;
		color: hsl(var(--foreground));
	}

	#tab_form_build .lead-form-builder .frmb .fbp-input {
		width: 100%;
		height: 40px;
		border: 1px solid hsl(var(--border));
		border-radius: 8px;
		background: hsl(var(--muted));
		color: hsl(var(--muted-foreground));
		padding: 9px 12px;
	}

	#tab_form_build .lead-form-builder .frmb textarea.fbp-input {
		min-height: 90px;
		resize: vertical;
	}

	#tab_form_build .lead-form-builder .frmb .fbp-file-row {
		display: flex;
		align-items: center;
		gap: 10px;
		border: 1px solid hsl(var(--border));
		background: hsl(var(--muted));
		border-radius: 8px;
		padding: 8px 10px;
	}

	#tab_form_build .lead-form-builder .frmb .fbp-file-btn {
		display: inline-flex;
		align-items: center;
		border: 1px solid hsl(var(--border));
		border-radius: 6px;
		background: hsl(var(--background));
		padding: 5px 8px;
		font-size: 12px;
		font-weight: 600;
		color: hsl(var(--foreground));
	}

	#tab_form_build .lead-form-builder .frmb .fbp-file-name {
		font-size: 12px;
		color: hsl(var(--muted-foreground));
	}

	#tab_form_build .lead-form-builder .frmb .fbp-hidden-file {
		position: absolute;
		left: -9999px;
		top: -9999px;
		opacity: 0;
		pointer-events: none;
		height: 0;
		width: 0;
	}

	#tab_form_build .lead-form-builder .frmb .fbp-heading {
		font-size: 24px;
		line-height: 1.25;
		font-weight: 650;
		color: hsl(var(--foreground));
		letter-spacing: 0;
	}

	#tab_form_build .lead-form-builder .frmb .fbp-paragraph .fbp-heading {
		font-size: 18px;
		letter-spacing: 0;
	}

	#tab_form_build .lead-form-builder .frmb .fbp-sub {
		margin-top: 6px;
		font-size: 13px;
		color: hsl(var(--muted-foreground));
	}

	#tab_form_build .lead-form-builder .stage-wrap .empty {
		color: hsl(var(--muted-foreground));
		font-size: 14px;
	}

	@media (max-width: 1024px) {
		.lead-builder-shell {
			grid-template-columns: 1fr;
		}

		.lead-builder-palette-list {
			max-height: 280px;
		}

		#tab_form_build .lead-form-builder .cb-wrap,
		#tab_form_build .lead-form-builder .stage-wrap {
			float: none !important;
			width: 100% !important;
		}

		#tab_form_build .lead-form-builder .cb-wrap {
			border-right: 0;
			border-bottom: 1px solid hsl(var(--border));
		}

		#tab_form_build .lead-form-builder .stage-wrap {
			min-height: 420px;
		}

		#tab_form_build .lead-form-builder .frmb {
			min-height: 430px;
		}
	}
</style>

<script>
	var buildWrap = document.getElementById('build-wrap');
	var formData = <?= json_encode(isset($formData) ? $formData : null); ?>;

	if (formData != null && formData.length < 1) {
		formData = formData.replace(/=\\/gm, "=''");
	}
</script>
<?php $this->load->view('admin/leads/_form_js_formatter'); ?>

<script>
	$(function() {
		var textBox = document.getElementById("foo");
		if (textBox) {
			textBox.onfocus = function() {
				textBox.select();
				textBox.onmouseup = function() {
					textBox.onmouseup = null;
					return false;
				};
			};
		}

		$('#showhide').on('change', function() {
			if ($(this).is(':checked')) {
				$('#shresult').slideUp(120);
			} else {
				$('#shresult').slideDown(120);
			}
		});

		var $leadTabs = $('[data-lead-tabs]');
		if ($leadTabs.length) {
			var activateLeadTab = function(target) {
				if (!target || !$(target).length) return;
				$leadTabs.find('li').removeClass('active');
				$leadTabs.find('a[href="' + target + '"]').closest('li').addClass('active');
				$('.lead-form-tab-content > .tab-pane').removeClass('active');
				$(target).addClass('active');
				if (target === '#tab_form_build' && typeof window.__initLeadBuilder === 'function') {
					window.__initLeadBuilder();
				}
				if (window.lucide && typeof window.lucide.createIcons === 'function') {
					window.lucide.createIcons();
				}
			};

			$leadTabs.on('click', 'a[href^="#tab_form_"]', function(e) {
				e.preventDefault();
				var target = $(this).attr('href');
				activateLeadTab(target);
				if (history.replaceState) {
					history.replaceState(null, '', target);
				}
			});

			var hashTarget = (window.location.hash || '').trim();
			if (hashTarget === '#tab_form_build' || hashTarget === '#tab_form_information') {
				activateLeadTab(hashTarget);
			} else {
				var $initial = $leadTabs.find('li.active a[href^="#tab_form_"]').first();
				if ($initial.length) {
					activateLeadTab($initial.attr('href'));
				}
			}
		}

		$('body').on('copy paste', 'input', function(e) {
			e.preventDefault();
		});

		$('body').on('blur', '.form-field.editing', function() {
			$.Shortcuts.start();
		});

		$('body').on('focus', '.form-field.editing', function() {
			$.Shortcuts.stop();
		});

			if (buildWrap) {
				var formBuilder = null;
				var builderInitialized = false;
				var initialFormDataRaw = formData;
				var fieldDefinitionMap = {};
			var allSets = []
				.concat(Array.isArray(db_fields) ? db_fields : [])
				.concat(Array.isArray(customFields) ? customFields : []);

			allSets.forEach(function(setItem) {
				if (!setItem || !Array.isArray(setItem.fields) || !setItem.fields.length) return;
				var firstField = $.extend(true, {}, setItem.fields[0]);
				var key = (setItem.name || firstField.name || '').toString();
				if (!key) return;
				fieldDefinitionMap[key] = firstField;
			});

			var resolvePaletteFieldDefinition = function(fieldType, fieldLabel) {
				if (!fieldType) return null;
				if (fieldDefinitionMap[fieldType]) {
					return $.extend(true, {}, fieldDefinitionMap[fieldType]);
				}
				if (fieldType === 'header') {
					return {
						type: 'header',
						subtype: 'h3',
						label: fieldLabel || 'Header'
					};
				}
				if (fieldType === 'paragraph') {
					return {
						type: 'paragraph',
						label: fieldLabel || 'Paragraph'
					};
				}
				if (fieldType === 'file') {
					return {
						type: 'file',
						label: fieldLabel || 'File Upload',
						name: 'file-input',
						className: 'form-control'
					};
				}
				return null;
			};

			var wirePaletteClickToAdd = function() {
				var $controlList = $(buildWrap).find('.frmb-control');
				if (!$controlList.length || $controlList.data('click-bound')) return;
				$controlList.data('click-bound', true);

				$controlList.on('click', 'li:not(.disabled)', function(e) {
					var $item = $(this);
					if ($item.hasClass('ui-sortable-helper') || $item.hasClass('form-field')) return;
					e.preventDefault();
					e.stopPropagation();

					var fieldType = ($item.attr('type') || $item.data('type') || '').toString();
					var fieldLabel = $.trim($item.text());
					if (!fieldType || !formBuilder.actions || typeof formBuilder.actions.addField !== 'function') return;

					var fieldDef = resolvePaletteFieldDefinition(fieldType, fieldLabel);
					if (!fieldDef) return;
					formBuilder.actions.addField(fieldDef);
				});
			};

			var wireCustomPaletteClickToAdd = function() {
				var $customPalette = $('[data-builder-palette]');
				if (!$customPalette.length || $customPalette.data('click-bound')) return;
				$customPalette.data('click-bound', true);

				$customPalette.on('click', '.js-builder-palette-item', function(e) {
					e.preventDefault();
					var $item = $(this);
					var fieldType = ($item.data('field-type') || '').toString();
					var fieldLabel = ($item.data('field-label') || '').toString();
					if (!fieldType) return;
					if (!builderInitialized && typeof window.__initLeadBuilder === 'function') {
						window.__initLeadBuilder();
					}
					if (!formBuilder || !formBuilder.actions || typeof formBuilder.actions.addField !== 'function') return;
					var fieldDef = resolvePaletteFieldDefinition(fieldType, fieldLabel);
					if (!fieldDef) return;
					formBuilder.actions.addField(fieldDef);
				});
			};

			window.__initLeadBuilder = function() {
				if (builderInitialized) {
					setTimeout(function() {
						var $sortable = $(buildWrap).find('.cb-wrap .ui-sortable');
						if ($sortable.length && $sortable.data('ui-sortable')) {
							$sortable.sortable('refresh');
						}
					}, 30);
					return;
				}
				formBuilder = $(buildWrap).formBuilder(fbOptions);
				builderInitialized = true;
				setTimeout(function() {
					$(".form-builder-save").wrap("<div class='btn-bottom-toolbar text-right'></div>");
					var $btnToolbar = $('body').find('#tab_form_build .btn-bottom-toolbar');
					$btnToolbar = $('#tab_form_build').append($btnToolbar);
					$btnToolbar.find('.btn').addClass('btn-info');
					wirePaletteClickToAdd();
					wireCustomPaletteClickToAdd();
				}, 100);
			};

			if (!$leadTabs.length || $('#tab_form_build').hasClass('active')) {
				window.__initLeadBuilder();
			}

			$('body').on('click', '.save_form_data', function() {
				if (!builderInitialized && typeof window.__initLeadBuilder === 'function') {
					window.__initLeadBuilder();
				}
				$.post(base_url + 'admin/leads/save_form_data', {
					formData: formBuilder.formData,
					form_id: $('input[name="form_id"]').val()
				}).done(function(response) {
					response = JSON.parse(response);
					if (response.success == true) {
						toastr['success'](response.message);
					}
				});
			});

			$('#form_info').on('submit', function() {
				var $holder = $('#lead_form_data');
				if (!$holder.length) return true;
				if (builderInitialized && formBuilder && typeof formBuilder.formData !== 'undefined') {
					$holder.val(formBuilder.formData);
				} else if (typeof initialFormDataRaw === 'string') {
					$holder.val(initialFormDataRaw);
				} else if (Array.isArray(initialFormDataRaw) || (initialFormDataRaw && typeof initialFormDataRaw === 'object')) {
					$holder.val(JSON.stringify(initialFormDataRaw));
				} else {
					$holder.val('');
				}
				return true;
			});
		}
	});
</script>

