<?php
/**
 * Basic Forms - Dedicated Form Editor Page
 * Custom layout (not WordPress post editor)
 *
 * @package BasicForms
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Admin\PageHero;

$form = $form ?? null;
$is_edit = $form && $form->ID > 0;
$form_id = $is_edit ? (int) $form->ID : 0;
$form_title = $is_edit ? $form->post_title : '';
$fields = $fields ?? [];
$settings = $settings ?? [];
$premium_unlocked = \BasicForms\FeatureGate::isPro();
$design = wp_parse_args( is_array( $design ) ? $design : [], \BasicForms\DesignDefaults::get() );
$defaults = [
	'recipient'               => get_option( 'admin_email' ),
	/* translators: %s: string value. */
	'subject'                 => sprintf( __( 'New form submission from %s', 'wppowersuite-lite' ), get_bloginfo( 'name' ) ),
	'success_message'         => __( 'Thank you! Your submission has been received.', 'wppowersuite-lite' ),
	'redirect_url'            => '',
	'submit_button_text'      => __( 'Submit', 'wppowersuite-lite' ),
	'enable_spam_protection'  => true,
	'captcha_provider'        => $premium_unlocked ? 'simple' : '',
	'enable_autoreply'        => false,
	'autoreply_subject'       => __( 'Thank you for your submission', 'wppowersuite-lite' ),
	'autoreply_message'       => __( 'We have received your submission and will get back to you soon.', 'wppowersuite-lite' ),
	'store_ip'                => true,
	'store_user_agent'        => true,
];
$settings = wp_parse_args( is_array( $settings ) ? $settings : [], $defaults );

$list_url = admin_url( 'admin.php?page=powersuite-basic-forms' );
$add_url = admin_url( 'admin.php?page=powersuite-basic-forms&action=add' );
$saved = isset( $_GET['saved'] ) && $_GET['saved'] === '1';

$publish_label = $is_edit ? __( 'Update Form', 'wppowersuite-lite' ) : __( 'Publish Form', 'wppowersuite-lite' );
$ai_enabled    = \BasicForms\FeatureGate::aiFormBuilderEnabled();
$form_design_enabled = \BasicForms\FeatureGate::formDesignEnabled();
$license_page_url = \BasicForms\FeatureGate::upsellUrl();
$ai_hero_btn   = '';
if ( $ai_enabled ) :
	ob_start();
	?>
<button type="button" class="button wpps-bf-open-ai-builder wpps-bf-ai-btn" id="wpps-bf-open-ai-builder-hero">
	<?php include __DIR__ . '/partials/ai-icon.php'; ?>
	<?php esc_html_e( 'Modify with AI', 'wppowersuite-lite' ); ?>
</button>
	<?php
	$ai_hero_btn = ob_get_clean();
endif;
ob_start();
?>
<button type="button" class="button<?php echo $form_design_enabled ? '' : ' wpps-bf-design-btn--locked'; ?>" id="wpps-bf-open-design"<?php echo $form_design_enabled ? '' : ' data-license-url="' . esc_url( $license_page_url ) . '"'; ?>>
	<span class="dashicons dashicons-art" aria-hidden="true"></span>
	<?php esc_html_e( 'Form Design', 'wppowersuite-lite' ); ?>
	<?php
	if ( ! $form_design_enabled && function_exists( 'wpps_render_premium_badge' ) ) {
		wpps_render_premium_badge();
	}
	?>
</button>
<?php
$design_btn = ob_get_clean();
$meta_html   = $ai_hero_btn . $design_btn . sprintf(
	' <a href="%1$s" class="button">%2$s</a> <button type="submit" form="wpps-bf-editor-form" class="button button-primary" id="wpps-bf-submit-btn"><span class="wpps-bf-btn-text"><span class="dashicons dashicons-saved" aria-hidden="true"></span> %3$s</span><span class="wpps-bf-btn-loader" style="display:none;"><span class="dashicons dashicons-update spin" aria-hidden="true"></span> %4$s</span></button>',
	esc_url( $add_url ),
	esc_html__( 'Add New Form', 'wppowersuite-lite' ),
	esc_html( $publish_label ),
	esc_html__( 'Saving...', 'wppowersuite-lite' )
);
?>
<div class="wrap wpps-bf-wrap wpps-bf-editor-page">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">

	<?php if ( $saved ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Form saved successfully.', 'wppowersuite-lite' ); ?></p></div>
	<?php endif; ?>

	<?php
	$bf_error = isset( $_GET['bf_error'] ) ? sanitize_key( wp_unslash( $_GET['bf_error'] ) ) : '';
	if ( '' !== $bf_error ) :
		$bf_messages = [
			'nonce'   => __( 'Your session expired before the form could be saved. Please reload this page and save again.', 'wppowersuite-lite' ),
			'cap'     => __( 'You do not have permission to save this form.', 'wppowersuite-lite' ),
			'title'   => __( 'Please enter a form title before saving.', 'wppowersuite-lite' ),
			'invalid' => __( 'This form could not be found or you cannot edit it.', 'wppowersuite-lite' ),
			'save'    => __( 'The form could not be saved. Please try again.', 'wppowersuite-lite' ),
		];
		$bf_message = $bf_messages[ $bf_error ] ?? __( 'The form could not be saved.', 'wppowersuite-lite' );
		?>
		<div class="notice notice-error is-dismissible"><p><?php echo esc_html( $bf_message ); ?></p></div>
	<?php endif; ?>

	<?php
	PageHero::render_for_module(
		[
			'icon'      => 'dashicons-feedback',
			'title'     => $is_edit ? __( 'Edit Form', 'wppowersuite-lite' ) : __( 'Create Form', 'wppowersuite-lite' ),
			'tagline'   => $is_edit
				? __( 'Edit fields, notifications, spam protection, and design for this form.', 'wppowersuite-lite' )
				: __( 'Build a new form with custom fields and email notifications.', 'wppowersuite-lite' ),
			'actions'   => [
				[
					'label' => __( 'All Forms', 'wppowersuite-lite' ),
					'url'   => $list_url,
					'icon'  => 'dashicons-arrow-left-alt',
				],
			],
			'meta_html' => $meta_html,
		]
	);
	?>

	<form id="wpps-bf-editor-form" method="post" class="wpps-bf-editor-form" novalidate>
		<?php wp_nonce_field( 'wpps_basic_forms_save', 'wpps_bf_editor_nonce' ); ?>
		<input type="hidden" name="wpps_bf_form_id" value="<?php echo (int) $form_id; ?>">

		<div class="wpps-bf-editor-main">
			<div class="wpps-bf-editor-content">
				<div class="wpps-bf-editor-section">
					<div class="wpps-bf-panel wpps-bf-editor-panel">
						<h2 class="wpps-bf-panel-title"><?php esc_html_e( 'Form Title', 'wppowersuite-lite' ); ?></h2>
						<div class="wpps-bf-panel-body">
							<p class="wpps-bf-panel-desc"><?php esc_html_e( 'Give your form a name for easy identification', 'wppowersuite-lite' ); ?></p>
							<input type="text" name="wpps_bf_form_title" id="wpps-bf-form-title" class="wpps-bf-input" value="<?php echo esc_attr( $form_title ); ?>" placeholder="<?php esc_attr_e( 'e.g., Contact Form', 'wppowersuite-lite' ); ?>" required>
						</div>
					</div>
				</div>

				<div class="wpps-bf-editor-section">
					<?php include __DIR__ . '/form-builder.php'; ?>
				</div>
			</div>

			<aside class="wpps-bf-editor-sidebar">
				<div class="wpps-bf-panel wpps-bf-sidebar-panel">
					<h2 class="wpps-bf-panel-title"><?php esc_html_e( 'Form Shortcode', 'wppowersuite-lite' ); ?></h2>
					<div class="wpps-bf-panel-body">
						<p class="wpps-bf-panel-desc"><?php esc_html_e( 'Use this shortcode to display the form', 'wppowersuite-lite' ); ?></p>
					<?php if ( $form_id > 0 ) : ?>
						<div class="wpps-bf-shortcode-wrap">
							<input type="text" readonly value='[basic_form id="<?php echo (int) $form_id; ?>"]' class="wpps-bf-input wpps-bf-shortcode-input" id="wpps-bf-shortcode-input" title="<?php esc_attr_e( 'Click to copy', 'wppowersuite-lite' ); ?>">
							<button type="button" class="wpps-bf-copy-btn" onclick="wppsBfCopyShortcode(document.getElementById('wpps-bf-shortcode-input'))" title="<?php esc_attr_e( 'Copy shortcode', 'wppowersuite-lite' ); ?>"><span class="dashicons dashicons-admin-page"></span></button>
							<span class="wpps-bf-shortcode-copied"><?php esc_html_e( 'Copied!', 'wppowersuite-lite' ); ?></span>
						</div>
					<?php else : ?>
						<p class="wpps-bf-muted"><?php esc_html_e( 'Save the form to get the shortcode.', 'wppowersuite-lite' ); ?></p>
					<?php endif; ?>
					</div>
				</div>

				<div class="wpps-bf-panel wpps-bf-sidebar-panel">
					<h2 class="wpps-bf-panel-title"><?php esc_html_e( 'Form Settings', 'wppowersuite-lite' ); ?></h2>
					<div class="wpps-bf-panel-body">
						<p class="wpps-bf-panel-desc"><?php esc_html_e( 'Email and submission options', 'wppowersuite-lite' ); ?></p>
						<div class="wpps-bf-settings-form">
						<div class="wpps-bf-form-group">
							<label for="wpps-bf-recipient"><?php esc_html_e( 'Email Recipient', 'wppowersuite-lite' ); ?></label>
							<input type="email" name="form_settings[recipient]" id="wpps-bf-recipient" class="wpps-bf-input" value="<?php echo esc_attr( $settings['recipient'] ?? '' ); ?>">
						</div>
						<div class="wpps-bf-form-group">
							<label for="wpps-bf-subject"><?php esc_html_e( 'Email Subject', 'wppowersuite-lite' ); ?></label>
							<input type="text" name="form_settings[subject]" id="wpps-bf-subject" class="wpps-bf-input" value="<?php echo esc_attr( $settings['subject'] ?? '' ); ?>">
						</div>
						<div class="wpps-bf-form-group">
							<label for="wpps-bf-success-message"><?php esc_html_e( 'Success Message', 'wppowersuite-lite' ); ?></label>
							<textarea name="form_settings[success_message]" id="wpps-bf-success-message" class="wpps-bf-input" rows="3"><?php echo esc_textarea( $settings['success_message'] ?? '' ); ?></textarea>
							<span class="wpps-bf-help"><?php esc_html_e( 'Shown after submission (if no redirect)', 'wppowersuite-lite' ); ?></span>
						</div>
						<div class="wpps-bf-form-group">
							<label for="wpps-bf-redirect">
								<?php esc_html_e( 'Redirect URL (optional)', 'wppowersuite-lite' ); ?>
								<?php
								if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_badge' ) ) {
									wpps_render_premium_badge();
								}
								?>
							</label>
							<input type="url" name="form_settings[redirect_url]" id="wpps-bf-redirect" class="wpps-bf-input" value="<?php echo esc_attr( $settings['redirect_url'] ?? '' ); ?>" placeholder="https://example.com/thank-you" <?php disabled( ! $premium_unlocked ); ?>>
						</div>
						<div class="wpps-bf-form-group">
							<label for="wpps-bf-submit-text"><?php esc_html_e( 'Submit Button Text', 'wppowersuite-lite' ); ?></label>
							<input type="text" name="form_settings[submit_button_text]" id="wpps-bf-submit-text" class="wpps-bf-input" value="<?php echo esc_attr( $settings['submit_button_text'] ?? '' ); ?>">
						</div>
						<?php
						$captcha_provider = $settings['captcha_provider'] ?? null;
						if ( $captcha_provider === null && ! empty( $settings['enable_spam_protection'] ) ) {
							$captcha_provider = $premium_unlocked ? 'simple' : '';
						}
						$captcha_provider = $captcha_provider ?? '';
						$captcha_premium_label = ! $premium_unlocked ? ' (' . esc_html__( 'Premium', 'wppowersuite-lite' ) . ')' : '';
						?>
						<div class="wpps-bf-form-group">
							<label for="wpps-bf-captcha-provider">
								<?php esc_html_e( 'Spam Protection', 'wppowersuite-lite' ); ?>
								<?php
								if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_badge' ) ) {
									wpps_render_premium_badge();
								}
								?>
							</label>
							<select id="wpps-bf-captcha-provider" name="form_settings[captcha_provider]" class="wpps-bf-input">
								<option value="" <?php selected( $captcha_provider, '' ); ?>><?php esc_html_e( 'None (honeypot + timing only)', 'wppowersuite-lite' ); ?></option>
								<option value="simple" <?php selected( $captcha_provider, 'simple' ); ?> <?php disabled( ! $premium_unlocked ); ?>><?php esc_html_e( 'Simple CAPTCHA', 'wppowersuite-lite' ); ?><?php echo $captcha_premium_label; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></option>
								<option value="google" <?php selected( $captcha_provider, 'google' ); ?> <?php disabled( ! $premium_unlocked ); ?>><?php esc_html_e( 'Google reCAPTCHA', 'wppowersuite-lite' ); ?><?php echo $captcha_premium_label; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></option>
								<option value="turnstile" <?php selected( $captcha_provider, 'turnstile' ); ?> <?php disabled( ! $premium_unlocked ); ?>><?php esc_html_e( 'Cloudflare Turnstile', 'wppowersuite-lite' ); ?><?php echo $captcha_premium_label; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></option>
							</select>
							<span class="wpps-bf-help"><?php esc_html_e( 'Honeypot and timing checks are always enabled. CAPTCHA options require a Premium license plus the corresponding module with AI Forms integration enabled in its settings.', 'wppowersuite-lite' ); ?></span>
						</div>
						<div class="wpps-bf-form-group">
							<label class="wpps-bf-checkbox-label">
								<input type="checkbox" name="form_settings[store_ip]" value="1" <?php checked( ! isset( $settings['store_ip'] ) || ! empty( $settings['store_ip'] ) ); ?>>
								<?php esc_html_e( 'Store submitter IP address', 'wppowersuite-lite' ); ?>
							</label>
							<span class="wpps-bf-help"><?php esc_html_e( 'Disable to reduce stored personal data when IP is not needed.', 'wppowersuite-lite' ); ?></span>
						</div>
						<div class="wpps-bf-form-group">
							<label class="wpps-bf-checkbox-label">
								<input type="checkbox" name="form_settings[store_user_agent]" value="1" <?php checked( ! isset( $settings['store_user_agent'] ) || ! empty( $settings['store_user_agent'] ) ); ?>>
								<?php esc_html_e( 'Store browser user agent', 'wppowersuite-lite' ); ?>
							</label>
						</div>
						<div class="wpps-bf-form-group">
							<label class="wpps-bf-checkbox-label" id="wpps-bf-autoreply-label">
								<input type="checkbox" name="form_settings[enable_autoreply]" value="1" <?php checked( ! empty( $settings['enable_autoreply'] ) ); ?> id="wpps-bf-enable-autoreply" <?php disabled( ! $premium_unlocked ); ?>>
								<?php esc_html_e( 'Send auto-reply email', 'wppowersuite-lite' ); ?>
								<?php
								if ( ! $premium_unlocked && function_exists( 'wpps_render_premium_badge' ) ) {
									wpps_render_premium_badge();
								}
								?>
							</label>
						</div>
						<div id="wpps-bf-autoreply-settings" class="wpps-bf-autoreply-settings" style="<?php echo empty( $settings['enable_autoreply'] ) ? 'display:none' : ''; ?>">
							<div class="wpps-bf-form-group">
								<label for="wpps-bf-autoreply-subject"><?php esc_html_e( 'Auto-reply Subject', 'wppowersuite-lite' ); ?></label>
								<input type="text" name="form_settings[autoreply_subject]" id="wpps-bf-autoreply-subject" class="wpps-bf-input" value="<?php echo esc_attr( $settings['autoreply_subject'] ?? '' ); ?>" <?php disabled( ! $premium_unlocked ); ?>>
							</div>
							<div class="wpps-bf-form-group">
								<label for="wpps-bf-autoreply-message"><?php esc_html_e( 'Auto-reply Message', 'wppowersuite-lite' ); ?></label>
								<textarea name="form_settings[autoreply_message]" id="wpps-bf-autoreply-message" class="wpps-bf-input" rows="4" <?php disabled( ! $premium_unlocked ); ?>><?php echo esc_textarea( $settings['autoreply_message'] ?? '' ); ?></textarea>
							</div>
						</div>
					</div>
				</div>

			</aside>
		</div>

		<?php
		$design_modal = is_readable( __DIR__ . '/form-design-modal.php' )
			? __DIR__ . '/form-design-modal.php'
			: '';
		if ( $design_modal !== '' ) {
			include $design_modal;
		}
		?>
	</form>

	<?php
	$ai_modal = is_readable( __DIR__ . '/partials/ai-form-builder-modal.php' )
		? __DIR__ . '/partials/ai-form-builder-modal.php'
		: '';
	if ( $ai_enabled && $ai_modal !== '' ) {
		$ai_mode = 'edit';
		include $ai_modal;
	}
	?>
</div>
<?php ob_start(); ?>
jQuery(function($){
	$('#wpps-bf-enable-autoreply').on('change', function(){
		$('#wpps-bf-autoreply-settings').toggle(this.checked);
	});
	// Color: circle -> hex sync
	$(document).on('input change', '.wpps-color-picker-circle.wpps-bf-design-color', function(){
		var id = $(this).attr('id');
		$('.wpps-color-code-input[data-color-input="' + id + '"]').val(this.value);
	});
	// Color: hex -> circle sync
	$(document).on('input', '.wpps-bf-design-color-hex', function(){
		var $t = $(this), v = $t.val(), id = $t.data('color-input');
		if (id && /^#[0-9A-Fa-f]{3,8}$/.test(v)) {
			var hex = v.length <= 4 ? v.replace(/([0-9A-Fa-f])/g, '$1$1') : v;
			if (hex.length === 7) $('#' + id).val(hex);
		}
	});
	// Design modal container - use for delegated handlers (events don't bubble to document due to stopPropagation)
	var $designContainer = $('#wpps-bf-design-modal .wpps-bf-design-modal-container');
	// Color reset
	$designContainer.on('click', '.wpps-color-reset', function(e){
		e.preventDefault();
		var def = $(this).data('default-color');
		var $wrap = $(this).closest('.wpps-color-code-wrap');
		var $hex = $wrap.find('.wpps-color-code-input');
		var id = $hex.data('color-input');
		$hex.val(def);
		if (id) $('#' + id).val(def);
	});
	// Typography toggle (delegated on container so it receives events despite stopPropagation)
	$designContainer.on('click', '.wpps-typography-toggle', function(e){
		e.preventDefault();
		var $wrap = $(this).closest('.wpps-typography-wrap');
		var $pop = $wrap.find('.wpps-typography-popover');
		var isOpen = $pop.css('display') === 'block' || $pop.is(':visible');
		$('#wpps-bf-design-modal .wpps-typography-popover').hide().css({ left: '', top: '' });
		$pop.toggle(!isOpen);
		if (!isOpen) {
			// Position fixed popover - prefer below toggle, flip above if not enough space
			var btn = $wrap.find('.wpps-typography-toggle')[0];
			if (btn) {
				var rect = btn.getBoundingClientRect();
				var popW = 340;
				var popH = Math.min(window.innerHeight * 0.7, 420);
				var left = rect.left;
				if (left + popW > window.innerWidth) left = window.innerWidth - popW - 8;
				if (left < 8) left = 8;
				var topBelow = rect.bottom + 8;
				var topAbove = rect.top - popH - 8;
				var top = topBelow;
				if (topBelow + popH > window.innerHeight - 16 && topAbove >= 16) {
					top = topAbove;
				} else if (topBelow + popH > window.innerHeight - 16) {
					top = Math.max(16, window.innerHeight - popH - 16);
				}
				$pop.css({ left: left + 'px', top: top + 'px' });
			} else {
				$pop[0].scrollIntoView({ block: 'nearest', behavior: 'smooth' });
			}
		}
	});
	// Device icons (typography responsive)
	$designContainer.on('click', '.wpps-device-icon', function(){
		var device = $(this).data('device');
		var $row = $(this).closest('.wpps-typography-responsive-row');
		$row.find('.wpps-device-icon').removeClass('is-active');
		$(this).addClass('is-active');
		$row.find('.wpps-font-size-wrap, .wpps-line-height-wrap, .wpps-letter-spacing-wrap').hide();
		$row.find('.wpps-font-size-' + device + ', .wpps-line-height-' + device + ', .wpps-letter-spacing-' + device).show();
	});
	// Font family preset -> custom / hidden sync
	$designContainer.on('change', '.wpps-font-family-preset', function(){
		var $pop = $(this).closest('.wpps-typography-popover');
		var val = $(this).val();
		if (val === '__custom__') {
			$pop.find('.wpps-font-family-custom-row').show();
			$pop.find('.wpps-font-family-custom').focus();
		} else {
			$pop.find('.wpps-font-family-custom-row').hide();
			$pop.find('.wpps-font-family-custom').val('');
			$pop.find('input[data-setting-key$="font_family"]').val(val || '');
		}
	});
	$designContainer.on('input', '.wpps-font-family-custom', function(){
		var $pop = $(this).closest('.wpps-typography-popover');
		$pop.find('input[data-setting-key$="font_family"]').val($(this).val());
	});
	// Number field clamping: shared src/Admin/Assets/number-clamp.js (data-wpps-min/max/step).
	$(document).on('click', function(e){
		if (!$(e.target).closest('.wpps-typography-popover, .wpps-typography-toggle').length) {
			$('.wpps-typography-popover').hide();
		}
	});
	$('#wpps-bf-editor-form').on('submit', function(){
		var $btn = $('#wpps-bf-submit-btn');
		if ($btn.length) {
			$btn.find('.wpps-bf-btn-text').hide();
			$btn.find('.wpps-bf-btn-loader').show();
			$btn.prop('disabled', true);
		}
	});
	$('#wpps-bf-open-design').on('click', function(){
		var $btn = $(this);
		if ($btn.hasClass('wpps-bf-design-btn--locked')) {
			var licenseUrl = $btn.data('license-url');
			if (licenseUrl) {
				window.location.href = licenseUrl;
			} else if (typeof wppsBfEditorData !== 'undefined' && wppsBfEditorData.strings && wppsBfEditorData.strings.premiumDesign) {
				alert(wppsBfEditorData.strings.premiumDesign);
			}
			return;
		}
		$('#wpps-bf-design-modal').addClass('show').attr('aria-hidden','false');
		$('body').css('overflow','hidden');
	});
	function closeDesignModal(){
		$('#wpps-bf-design-modal').removeClass('show').attr('aria-hidden','true');
		$('body').css('overflow','');
	}
	$('.wpps-bf-design-modal-close, #wpps-bf-design-modal').on('click', function(e){
		if (e.target === this || $(e.target).hasClass('wpps-bf-design-modal-close')) closeDesignModal();
	});
	$designContainer.on('click', function(e){
		e.stopPropagation();
		if (!$(e.target).closest('.wpps-typography-popover, .wpps-typography-toggle').length) {
			$('#wpps-bf-design-modal .wpps-typography-popover').hide();
		}
	});
	window.wppsBfSyncDesignModalFromSaved = function (formDesign) {
		if (!formDesign || typeof formDesign !== 'object') return;
		$.each(formDesign, function(k, v) {
			var $el = $('#wpps-bf-design-modal').find('[name="form_design[' + k + ']"]');
			if (!$el.length) return;
			if ($el.is(':checkbox')) {
				$el.prop('checked', v === '1' || v === 1);
			} else {
				$el.val(v === null || v === undefined ? '' : String(v));
			}
			if ($el.hasClass('wpps-bf-design-color')) {
				var cid = $el.attr('id');
				if (cid) {
					$('.wpps-color-code-input[data-color-input="' + cid + '"]').val(v);
				}
			}
		});
		$('#wpps-bf-design-modal .wpps-typography-popover').each(function() {
			var $pop = $(this);
			var $hidden = $pop.find('input[type="hidden"][data-setting-key$="font_family"]');
			if (!$hidden.length) return;
			var val = $hidden.val() || '';
			var $preset = $pop.find('.wpps-font-family-preset');
			var $custom = $pop.find('.wpps-font-family-custom');
			var presets = $preset.find('option').map(function() { return $(this).val(); }).get();
			if (presets.indexOf(val) >= 0) {
				$preset.val(val);
				$pop.find('.wpps-font-family-custom-row').hide();
				$custom.val('');
			} else if (val) {
				$preset.val('__custom__');
				$pop.find('.wpps-font-family-custom-row').show();
				$custom.val(val);
			} else {
				$preset.val($preset.find('option:first').val() || '');
				$pop.find('.wpps-font-family-custom-row').hide();
				$custom.val('');
			}
		});
	};
	function wppsBfCollectDesignFromModal() {
		var formDesign = {};
		$('#wpps-bf-design-modal').find('[name^="form_design["]').each(function(){
			var $el = $(this), name = $el.attr('name'), m = name.match(/^form_design\[([^\]]+)\]$/);
			if (m) {
				if ($el.is(':checkbox')) formDesign[m[1]] = $el.is(':checked') ? '1' : '';
				else formDesign[m[1]] = $el.val() || '';
			}
		});
		return formDesign;
	}
	window.wppsBfSaveDesignFromModal = function () {
		var formId = parseInt($('input[name="wpps_bf_form_id"]').val(), 10);
		if (formId <= 0) {
			return $.Deferred().resolve().promise();
		}
		return $.post(typeof wppsBfEditorData !== 'undefined' ? wppsBfEditorData.ajaxUrl : ajaxurl, {
			action: 'wpps_basic_forms_save_design',
			nonce: typeof wppsBfEditorData !== 'undefined' ? wppsBfEditorData.saveNonce : $('input[name="wpps_bf_editor_nonce"]').val(),
			form_id: formId,
			form_design: wppsBfCollectDesignFromModal()
		}).then(function (r) {
			if (r.success && r.data && r.data.form_design) {
				window.wppsBfSyncDesignModalFromSaved(r.data.form_design);
			}
			return r;
		});
	};
	$('#wpps-bf-design-apply').on('click', function(){
		var $btn = $(this), formId = parseInt($('input[name="wpps_bf_form_id"]').val(), 10);
		if (formId <= 0) {
			alert('<?php echo esc_js( __( 'Please save the form first to apply design changes.', 'wppowersuite-lite' ) ); ?>');
			return;
		}
		$btn.prop('disabled', true);
		$btn.find('.wpps-bf-apply-text').hide();
		$btn.find('.wpps-bf-apply-loader').show();
		window.wppsBfSaveDesignFromModal().done(function(r){
			if (r.success) {
				$btn.find('.wpps-bf-apply-text').text('<?php echo esc_js( __( 'Saved', 'wppowersuite-lite' ) ); ?>').show();
				$btn.find('.wpps-bf-apply-loader').hide();
				setTimeout(function(){ $btn.find('.wpps-bf-apply-text').text('<?php echo esc_js( __( 'Apply', 'wppowersuite-lite' ) ); ?>'); }, 2000);
			} else {
				alert(r.data && r.data.message ? r.data.message : '<?php echo esc_js( __( 'Error saving design.', 'wppowersuite-lite' ) ); ?>');
				$btn.find('.wpps-bf-apply-text').show();
				$btn.find('.wpps-bf-apply-loader').hide();
			}
			$btn.prop('disabled', false);
		}).fail(function(){
			alert('<?php echo esc_js( __( 'Network error. Please try again.', 'wppowersuite-lite' ) ); ?>');
			$btn.find('.wpps-bf-apply-text').show();
			$btn.find('.wpps-bf-apply-loader').hide();
			$btn.prop('disabled', false);
		});
	});
	$(document).on('keydown', function(e){
		if (e.key === 'Escape' && $('#wpps-bf-design-modal').hasClass('show')) closeDesignModal();
	});
	$('.wpps-bf-design-tab').on('click', function(){
		var tab = $(this).data('tab');
		$('.wpps-bf-design-tab').removeClass('is-active');
		$(this).addClass('is-active');
		$('.wpps-bf-design-panel').removeClass('is-active');
		$('.wpps-bf-design-panel[data-panel="' + tab + '"]').addClass('is-active');
	});
	$('select[name="form_design[layout]"]').on('change', function(){
		$('.wpps-bf-design-max-width').toggle($(this).val() === 'custom');
	});
	$('#wpps-bf-design-reset').on('click', function(){
		var def = $('#wpps-bf-design-modal').data('defaults');
		if (!def || typeof def !== 'object') return;
		$.each(def, function(k, v){
			var $el = $('#wpps-bf-design-modal').find('[name="form_design[' + k + ']"]');
			if ($el.length) {
				if ($el.is(':checkbox')) $el.prop('checked', v === '1' || v === 1);
				else $el.val(v);
			}
		});
		$('#wpps-bf-design-modal input[type="color"]').each(function(){
			var id = $(this).attr('id');
			var key = id.replace('wpps-bf-design-','').replace(/-/g,'_');
			var keyMap = { bg_color:'bg_color', border_color:'border_color', label_color:'label_color', input_border_color:'input_border_color', input_bg:'input_bg', placeholder_color:'placeholder_color', field_text_color:'field_text_color', help_text_color:'help_text_color', primary_color:'primary_color', button_hover_color:'button_hover_color', button_border_color:'button_border_color', success_bg:'success_msg_bg', success_color:'success_msg_color', success_border:'success_msg_border', error_bg:'error_msg_bg', error_color:'error_msg_color', error_border:'error_msg_border' };
			var dk = keyMap[key] || key;
			if (def[dk]) { $(this).val(def[dk]); $('.wpps-color-code-input[data-color-input="' + id + '"]').val(def[dk]); }
		});
		$('#wpps-bf-design-modal .wpps-typography-popover').each(function(){
			var $pop = $(this);
			var $hidden = $pop.find('input[data-setting-key$="font_family"]');
			var val = $hidden.val() || '';
			var $preset = $pop.find('.wpps-font-family-preset');
			var $custom = $pop.find('.wpps-font-family-custom');
			var presets = $preset.find('option').map(function(){ return $(this).val(); }).get();
			if (presets.indexOf(val) >= 0) {
				$preset.val(val);
				$pop.find('.wpps-font-family-custom-row').hide();
				$custom.val('');
			} else if (val) {
				$preset.val('__custom__');
				$pop.find('.wpps-font-family-custom-row').show();
				$custom.val(val);
			} else {
				$preset.val('');
				$pop.find('.wpps-font-family-custom-row').hide();
				$custom.val('');
			}
		});
	});
});
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-basic-forms-views-form-editor-php-script-1', (string) ob_get_clean() ); ?>

