<?php
/**
 * Custom Fields - add/edit view (field group builder).
 *
 * Layout: group identity first, the fields builder front and center, and a
 * collapsible Settings section (Location / Presentation / Usage tabs) below.
 *
 * @package CustomFields
 *
 * @var \CustomFields\Admin                     $admin
 * @var array<string, mixed>                    $definition
 * @var bool                                    $is_edit
 * @var array{type: string, text: string}|null  $notice
 * @var array<int, string>                      $errors
 * @var array<string, string>                   $post_types
 * @var array<string, string>                   $taxonomies
 * @var array<string, string>                   $taxonomy_terms
 * @var array<string, string>                   $page_templates
 */

namespace CustomFields;

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

require_once __DIR__ . '/field-row.php';

$definition = isset( $definition ) && is_array( $definition ) ? $definition : Config::defaultGroup();
$is_edit    = ! empty( $is_edit );
$errors     = isset( $errors ) && is_array( $errors ) ? $errors : [];
$post_types = isset( $post_types ) && is_array( $post_types ) ? $post_types : [];
$taxonomies     = isset( $taxonomies ) && is_array( $taxonomies ) ? $taxonomies : [];
$taxonomy_terms = isset( $taxonomy_terms ) && is_array( $taxonomy_terms ) ? $taxonomy_terms : [];
$page_templates = isset( $page_templates ) && is_array( $page_templates ) ? $page_templates : [];

$key         = (string) ( $definition['key'] ?? '' );
$title       = (string) ( $definition['title'] ?? '' );
$enabled     = ! empty( $definition['enabled'] );
$position    = (string) ( $definition['position'] ?? 'normal' );
$priority    = (string) ( $definition['priority'] ?? 'default' );
$style       = (string) ( $definition['style'] ?? 'default' );
$show_in_rest = ! empty( $definition['show_in_rest'] );
$location    = isset( $definition['location'] ) && is_array( $definition['location'] ) ? $definition['location'] : [];
$location_rules = LocationRules::get( $definition );
$loc_screen     = (string) ( $location_rules['screen'] ?? 'post' );
$loc_match      = (string) ( $location_rules['match'] ?? 'all' );
$loc_rules      = isset( $location_rules['rules'] ) && is_array( $location_rules['rules'] ) ? $location_rules['rules'] : [];
$fields         = isset( $definition['fields'] ) && is_array( $definition['fields'] ) ? $definition['fields'] : [];
$usage_fields   = [];
if ( $is_edit && $key !== '' ) {
	foreach ( array_values( $fields ) as $field ) {
		if ( ! is_array( $field ) ) {
			continue;
		}
		$type = (string) ( $field['type'] ?? 'text' );
		if ( ! Config::storesValue( $type ) ) {
			continue;
		}
		$storage_key = (string) ( $field['name'] ?? '' );
		if ( $storage_key === '' ) {
			$storage_key = (string) ( $field['key'] ?? '' );
		}
		if ( $storage_key === '' ) {
			continue;
		}
		$usage_fields[] = [
			'label' => (string) ( $field['label'] ?? $storage_key ),
			'key'   => $storage_key,
		];
	}
}
$usage_sample_key = $usage_fields[0]['key'] ?? 'field_key';
$field_targets  = isset( $field_targets ) && is_array( $field_targets ) ? $field_targets : [];
$clone_targets  = isset( $clone_targets ) && is_array( $clone_targets ) ? $clone_targets : [];
$field_key_opts = isset( $field_key_opts ) && is_array( $field_key_opts ) ? $field_key_opts : [];
$rule_value_choices = isset( $rule_value_choices ) && is_array( $rule_value_choices ) ? $rule_value_choices : [];

/**
 * Render the rule value control: a dropdown when the parameter has a known
 * set of values, a text input otherwise. Both controls are always present;
 * the inactive one is hidden and disabled so it never submits. JS swaps
 * them when the parameter changes.
 *
 * @param string $param Rule parameter.
 * @param string $value Current value.
 * @param string $name  Input name attribute.
 */
$cf_render_rule_value = static function ( string $param, string $value, string $name ) use ( $rule_value_choices ): void {
	$choices    = isset( $rule_value_choices[ $param ] ) && is_array( $rule_value_choices[ $param ] ) ? $rule_value_choices[ $param ] : [];
	$use_select = $choices !== [];
	$input_type = in_array( $param, Config::numericLocationRuleParams(), true ) ? 'number' : 'text';
	?>
	<select class="cf-rule-value-select" name="<?php echo esc_attr( $name ); ?>"<?php echo $use_select ? '' : ' hidden disabled'; ?>>
		<?php if ( $value !== '' && ! isset( $choices[ $value ] ) ) : ?>
			<option value="<?php echo esc_attr( $value ); ?>" selected><?php echo esc_html( $value ); ?></option>
		<?php endif; ?>
		<?php foreach ( $choices as $c_val => $c_label ) : ?>
			<option value="<?php echo esc_attr( (string) $c_val ); ?>" <?php selected( $value, (string) $c_val ); ?>><?php echo esc_html( (string) $c_label ); ?></option>
		<?php endforeach; ?>
	</select>
	<input type="<?php echo esc_attr( $input_type ); ?>" class="regular-text cf-rule-value" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $use_select ? '' : $value ); ?>" placeholder="<?php esc_attr_e( 'Value', 'wppowersuite-lite' ); ?>"<?php echo $input_type === 'number' ? ' inputmode="numeric" step="1" min="0"' : ''; ?><?php echo $use_select ? ' hidden disabled' : ''; ?>>
	<?php
};

/**
 * Render location-rule operator choices for the current parameter.
 *
 * @param string $param    Rule parameter.
 * @param string $selected Selected operator.
 * @param string $name     Select name attribute.
 */
$cf_render_rule_operator = static function ( string $param, string $selected, string $name ): void {
	$operators = Config::locationRuleOperatorsForParam( $param );
	if ( ! array_key_exists( $selected, $operators ) ) {
		$selected = '==';
	}
	?>
	<select name="<?php echo esc_attr( $name ); ?>" class="cf-rule-operator">
		<?php foreach ( $operators as $op_key => $op_label ) : ?>
			<option value="<?php echo esc_attr( $op_key ); ?>" <?php selected( $selected, $op_key ); ?>><?php echo esc_html( $op_label ); ?></option>
		<?php endforeach; ?>
	</select>
	<?php
};

$cf_type_icons = [
	'text'             => 'dashicons-editor-textcolor',
	'textarea'         => 'dashicons-text-page',
	'number'           => 'dashicons-editor-ol',
	'range'            => 'dashicons-leftright',
	'email'            => 'dashicons-email-alt',
	'phone'            => 'dashicons-phone',
	'url'              => 'dashicons-admin-links',
	'password'         => 'dashicons-lock',
	'date'             => 'dashicons-calendar-alt',
	'time'             => 'dashicons-clock',
	'datetime'         => 'dashicons-calendar',
	'color'            => 'dashicons-art',
	'toggle'           => 'dashicons-yes-alt',
	'select'           => 'dashicons-menu-alt',
	'radio'            => 'dashicons-marker',
	'checkbox'         => 'dashicons-yes',
	'button_group'     => 'dashicons-editor-kitchensink',
	'nav_menu'         => 'dashicons-menu-alt',
	'message'          => 'dashicons-info-outline',
	'separator'        => 'dashicons-minus',
	'output'           => 'dashicons-editor-code',
	'tab'              => 'dashicons-index-card',
	'accordion'        => 'dashicons-menu-alt3',
	'icon_picker'      => 'dashicons-star-filled',
	'google_map'       => 'dashicons-location',
	'wysiwyg'          => 'dashicons-edit-page',
	'oembed'           => 'dashicons-embed-generic',
	'link'             => 'dashicons-admin-links',
	'image'            => 'dashicons-format-image',
	'gallery'          => 'dashicons-format-gallery',
	'file'             => 'dashicons-media-default',
	'post_object'      => 'dashicons-admin-post',
	'relationship'     => 'dashicons-networking',
	'page_link'        => 'dashicons-admin-links',
	'term'             => 'dashicons-tag',
	'user'             => 'dashicons-admin-users',
	'group'            => 'dashicons-plus-alt',
	'repeater'         => 'dashicons-list-view',
	'flexible_content' => 'dashicons-layout',
	'clone'            => 'dashicons-admin-page',
];

$cf_quick_field_groups = [];
foreach ( Config::fieldTypes() as $type_key => $type_data ) {
	$group_label = (string) ( $type_data['group'] ?? __( 'Other', 'wppowersuite-lite' ) );
	$cf_quick_field_groups[ $group_label ][ $type_key ] = (string) ( $type_data['label'] ?? $type_key );
}
?>
<div class="wrap wpps-cf wpps-cf-edit">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">
	<?php
	\WP_PowerSuite\Admin\PageHero::render_for_module(
		[
			'icon'    => 'dashicons-list-view',
			'title'   => $is_edit ? __( 'Edit Field Group', 'wppowersuite-lite' ) : __( 'Add Field Group', 'wppowersuite-lite' ),
			'tagline' => __( 'Define fields and choose where they appear.', 'wppowersuite-lite' ),
			'actions' => [
				[
					'label' => __( 'All Field Groups', 'wppowersuite-lite' ),
					'url'   => $admin->url(),
					'icon'  => 'dashicons-arrow-left-alt',
				],
			],
		]
	);
	?>

	<?php if ( $notice !== null ) : ?>
		<div class="notice notice-<?php echo esc_attr( $notice['type'] ); ?> is-dismissible" data-wpps-plugin="true">
			<p><?php echo esc_html( $notice['text'] ); ?></p>
		</div>
	<?php endif; ?>

	<?php
	$prefill_post_type = isset( $_GET['for_post_type'] ) ? sanitize_key( wp_unslash( (string) $_GET['for_post_type'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$prefill_taxonomy  = isset( $_GET['for_taxonomy'] ) ? sanitize_key( wp_unslash( (string) $_GET['for_taxonomy'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( ! $is_edit && $prefill_post_type !== '' && post_type_exists( $prefill_post_type ) ) :
		$pt_object = get_post_type_object( $prefill_post_type );
		$pt_label  = $pt_object instanceof \WP_Post_Type ? (string) $pt_object->labels->singular_name : $prefill_post_type;
		?>
		<div class="notice notice-info" data-wpps-plugin="true">
			<p>
				<?php
				printf(
					/* translators: %s: post type singular label. */
					esc_html__( 'Location rules are pre-filled for the “%s” post type. Add your fields and save the group.', 'wppowersuite-lite' ),
					esc_html( $pt_label )
				);
				?>
			</p>
		</div>
	<?php elseif ( ! $is_edit && $prefill_taxonomy !== '' && taxonomy_exists( $prefill_taxonomy ) ) : ?>
		<?php
		$tax_object = get_taxonomy( $prefill_taxonomy );
		$tax_label  = $tax_object instanceof \WP_Taxonomy ? (string) $tax_object->labels->singular_name : $prefill_taxonomy;
		?>
		<div class="notice notice-info" data-wpps-plugin="true">
			<p>
				<?php
				printf(
					/* translators: %s: taxonomy singular label. */
					esc_html__( 'Location rules are pre-filled for the “%s” taxonomy. Add your fields and save the group.', 'wppowersuite-lite' ),
					esc_html( $tax_label )
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<?php if ( $errors !== [] ) : ?>
		<div class="cf-error-box" role="alert">
			<p><strong><?php esc_html_e( 'Your changes were not saved. Please fix the following:', 'wppowersuite-lite' ); ?></strong></p>
			<ul class="cf-error-list">
				<?php foreach ( $errors as $error ) : ?>
					<li><?php echo esc_html( $error ); ?></li>
				<?php endforeach; ?>
			</ul>
		</div>
	<?php endif; ?>

	<form method="post" action="<?php echo esc_url( $admin->postEndpoint() ); ?>" class="cf-form" id="cf-form">
		<input type="hidden" name="action" value="wpps_cf_save">
		<?php wp_nonce_field( 'wpps_cf_save' ); ?>
		<input type="hidden" name="original_key" value="<?php echo esc_attr( $is_edit ? $key : '' ); ?>">

		<div class="cf-actions-bar cf-actions-bar--top">
			<div class="cf-save-cluster">
				<label class="cf-switch cf-switch--enabled">
					<input type="checkbox" name="enabled" value="1" <?php checked( $enabled ); ?>>
					<span class="cf-switch__track" aria-hidden="true"><span class="cf-switch__thumb"></span></span>
					<span class="cf-switch__label"><?php esc_html_e( 'Enabled', 'wppowersuite-lite' ); ?></span>
				</label>
				<button type="submit" class="button button-primary">
					<?php echo $is_edit ? esc_html__( 'Save Changes', 'wppowersuite-lite' ) : esc_html__( 'Create Field Group', 'wppowersuite-lite' ); ?>
				</button>
			</div>
		</div>

		<div class="cf-builder-layout">
			<main class="cf-builder-main">
				<div class="cf-card cf-card--fields">
					<div class="cf-card__head">
						<div>
							<h2><?php esc_html_e( 'Fields', 'wppowersuite-lite' ); ?></h2>
							<p class="description"><?php esc_html_e( 'Drag fields to control their order. Use width to place compatible fields side by side on the edit screen.', 'wppowersuite-lite' ); ?></p>
						</div>
						<div class="cf-add-field-menu">
							<button type="button" class="button button-secondary cf-open-field-type-menu" id="cf-add-field" aria-expanded="false" aria-controls="cf-field-type-menu">
								<span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
								<?php esc_html_e( 'Add Field', 'wppowersuite-lite' ); ?>
							</button>
							<div class="cf-field-type-menu" id="cf-field-type-menu" role="dialog" aria-modal="false" aria-labelledby="cf-field-type-menu-title" tabindex="-1" hidden>
								<div class="cf-field-type-menu__head">
									<div>
										<strong id="cf-field-type-menu-title"><?php esc_html_e( 'Choose Field Type', 'wppowersuite-lite' ); ?></strong>
										<span><?php esc_html_e( 'Select a type to add it to this group.', 'wppowersuite-lite' ); ?></span>
									</div>
									<button type="button" class="cf-field-type-menu__close" aria-label="<?php esc_attr_e( 'Close field type menu', 'wppowersuite-lite' ); ?>">
										<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
									</button>
								</div>
								<?php foreach ( $cf_quick_field_groups as $quick_group => $quick_types ) : ?>
									<div class="cf-field-type-menu__group">
										<span class="cf-field-type-menu__label"><?php echo esc_html( $quick_group ); ?></span>
										<div class="cf-field-type-menu__grid">
											<?php foreach ( $quick_types as $quick_type => $quick_label ) : ?>
												<button type="button" class="cf-quick-add-btn" data-cf-add-type="<?php echo esc_attr( $quick_type ); ?>" title="<?php echo esc_attr( $quick_label ); ?>">
													<span class="dashicons <?php echo esc_attr( $cf_type_icons[ $quick_type ] ?? 'dashicons-plus-alt2' ); ?>" aria-hidden="true"></span>
													<span><?php echo esc_html( $quick_label ); ?></span>
												</button>
											<?php endforeach; ?>
										</div>
									</div>
								<?php endforeach; ?>
							</div>
						</div>
					</div>
					<div class="cf-fields-list" id="cf-fields-list">
						<?php if ( $fields === [] ) : ?>
							<div class="cf-fields-empty">
								<strong><?php esc_html_e( 'No fields yet', 'wppowersuite-lite' ); ?></strong>
								<span><?php esc_html_e( 'Use Add Field to choose a field type.', 'wppowersuite-lite' ); ?></span>
							</div>
						<?php else : ?>
							<?php foreach ( array_values( $fields ) as $index => $field ) : ?>
								<?php cf_render_field_row( (int) $index, is_array( $field ) ? $field : [], $post_types, $taxonomies, $key, $field_targets, $field_key_opts, $clone_targets, $taxonomy_terms ); ?>
							<?php endforeach; ?>
						<?php endif; ?>
					</div>
					<div class="cf-fields-list-footer">
						<button type="button" class="button button-secondary cf-open-field-type-menu" aria-expanded="false" aria-controls="cf-field-type-menu">
							<span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
							<?php esc_html_e( 'Add Field', 'wppowersuite-lite' ); ?>
						</button>
					</div>
				</div>

				<details class="cf-settings cf-settings--locations" id="cf-settings" open>
					<summary>
						<span class="dashicons dashicons-location" aria-hidden="true"></span>
						<?php esc_html_e( 'Location Rules', 'wppowersuite-lite' ); ?>
					</summary>
					<div class="cf-settings__inner">
						<div class="cf-sidebar-control">
							<label for="cf-loc-match"><?php esc_html_e( 'Rule matching', 'wppowersuite-lite' ); ?></label>
							<select id="cf-loc-match" name="location_rules[match]">
								<option value="all" <?php selected( $loc_match, 'all' ); ?>><?php esc_html_e( 'Match all rules (AND)', 'wppowersuite-lite' ); ?></option>
								<option value="any" <?php selected( $loc_match, 'any' ); ?>><?php esc_html_e( 'Match any rule (OR)', 'wppowersuite-lite' ); ?></option>
							</select>
						</div>
						<div id="cf-location-rules-list" class="cf-rules-list">
							<?php if ( $loc_rules === [] ) : ?>
								<p class="cf-rules-empty"><?php esc_html_e( 'No rules yet.', 'wppowersuite-lite' ); ?></p>
							<?php else : ?>
								<?php foreach ( array_values( $loc_rules ) as $ri => $rule ) : ?>
									<?php if ( ! is_array( $rule ) ) { continue; } ?>
									<div class="cf-rule-row" data-index="<?php echo esc_attr( (string) $ri ); ?>">
										<select name="location_rules[rules][<?php echo esc_attr( (string) $ri ); ?>][param]" class="cf-rule-param">
											<?php foreach ( Config::locationRuleParams() as $p_key => $p_label ) : ?>
												<option value="<?php echo esc_attr( $p_key ); ?>" <?php selected( (string) ( $rule['param'] ?? '' ), $p_key ); ?>><?php echo esc_html( $p_label ); ?></option>
											<?php endforeach; ?>
										</select>
										<?php $cf_render_rule_operator( (string) ( $rule['param'] ?? 'post_type' ), (string) ( $rule['operator'] ?? '==' ), 'location_rules[rules][' . (string) $ri . '][operator]' ); ?>
										<?php $cf_render_rule_value( (string) ( $rule['param'] ?? 'post_type' ), (string) ( $rule['value'] ?? '' ), 'location_rules[rules][' . (string) $ri . '][value]' ); ?>
										<button type="button" class="button-link cf-rule-remove" aria-label="<?php esc_attr_e( 'Remove rule', 'wppowersuite-lite' ); ?>">&times;</button>
									</div>
								<?php endforeach; ?>
							<?php endif; ?>
						</div>
						<p>
							<button type="button" class="button button-secondary cf-add-location-rule" id="cf-add-location-rule">
								<span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
								<?php esc_html_e( 'Add rule', 'wppowersuite-lite' ); ?>
							</button>
						</p>
						<template id="cf-location-rule-template">
							<div class="cf-rule-row" data-index="__INDEX__">
								<select name="location_rules[rules][__INDEX__][param]" class="cf-rule-param">
									<?php foreach ( Config::locationRuleParams() as $p_key => $p_label ) : ?>
										<option value="<?php echo esc_attr( $p_key ); ?>"><?php echo esc_html( $p_label ); ?></option>
									<?php endforeach; ?>
								</select>
								<?php $cf_render_rule_operator( 'post_type', '==', 'location_rules[rules][__INDEX__][operator]' ); ?>
								<?php $cf_render_rule_value( 'post_type', '', 'location_rules[rules][__INDEX__][value]' ); ?>
								<button type="button" class="button-link cf-rule-remove" aria-label="<?php esc_attr_e( 'Remove rule', 'wppowersuite-lite' ); ?>">&times;</button>
							</div>
						</template>
					</div>
				</details>

				<div class="cf-actions-bar cf-actions-bar--bottom">
					<?php if ( $is_edit ) : ?>
						<a href="<?php echo esc_url( $admin->actionUrl( 'wpps_cf_delete', 'wpps_cf_delete_' . $key, [ 'key' => $key ] ) ); ?>" class="button button-link-delete cf-delete">
							<?php esc_html_e( 'Delete Field Group', 'wppowersuite-lite' ); ?>
						</a>
					<?php endif; ?>
					<button type="submit" class="button button-primary">
						<?php echo $is_edit ? esc_html__( 'Save Changes', 'wppowersuite-lite' ) : esc_html__( 'Create Field Group', 'wppowersuite-lite' ); ?>
					</button>
				</div>
			</main>

			<aside class="cf-builder-sidebar">
				<div class="cf-card cf-card--identity">
					<h2><?php esc_html_e( 'Group Setup', 'wppowersuite-lite' ); ?></h2>
					<div class="cf-sidebar-control">
						<label for="cf-title"><?php esc_html_e( 'Title', 'wppowersuite-lite' ); ?> <span class="cf-req">*</span></label>
						<input type="text" id="cf-title" name="title" value="<?php echo esc_attr( $title ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. Book Details', 'wppowersuite-lite' ); ?>" required>
						<p class="description"><?php esc_html_e( 'Shown as the field panel heading on matching edit screens.', 'wppowersuite-lite' ); ?></p>
					</div>
					<div class="cf-sidebar-control">
						<label for="cf-key"><?php esc_html_e( 'Group key', 'wppowersuite-lite' ); ?> <span class="cf-req">*</span></label>
						<?php if ( $is_edit ) : ?>
							<code class="cf-key-readonly" id="cf-key" data-cf-group-key-readonly><?php echo esc_html( $key ); ?></code>
							<p class="description"><?php esc_html_e( 'Locked after creation so saved field values keep their storage keys.', 'wppowersuite-lite' ); ?></p>
						<?php else : ?>
							<input type="text" id="cf-key" name="key" value="<?php echo esc_attr( $key ); ?>" class="regular-text" maxlength="<?php echo esc_attr( (string) Config::MAX_KEY_LENGTH ); ?>" pattern="[a-z][a-z0-9_]*" required>
							<p class="description"><?php esc_html_e( 'Generated automatically. You can edit it before the first save.', 'wppowersuite-lite' ); ?></p>
						<?php endif; ?>
					</div>
				</div>

				<div class="cf-card cf-card--settings">
					<h2><?php esc_html_e( 'Where It Appears', 'wppowersuite-lite' ); ?></h2>
					<div class="cf-sidebar-control">
						<label for="cf-loc-screen"><?php esc_html_e( 'Editing screen', 'wppowersuite-lite' ); ?></label>
						<select id="cf-loc-screen" name="location_rules[screen]">
							<option value="post" <?php selected( $loc_screen, 'post' ); ?>><?php esc_html_e( 'Posts, pages, or CPTs', 'wppowersuite-lite' ); ?></option>
							<option value="taxonomy" <?php selected( $loc_screen, 'taxonomy' ); ?>><?php esc_html_e( 'Taxonomy terms', 'wppowersuite-lite' ); ?></option>
						</select>
					</div>
					<div class="cf-sidebar-control">
						<label for="cf-position"><?php esc_html_e( 'Field position', 'wppowersuite-lite' ); ?></label>
						<div class="cf-position-picker cf-position-row" id="cf-position"<?php echo $loc_screen === 'post' ? '' : ' hidden'; ?>>
							<?php foreach ( Config::positions() as $pos_key => $pos_label ) : ?>
								<label class="cf-position-option">
									<input type="radio" name="position" value="<?php echo esc_attr( $pos_key ); ?>" <?php checked( ( $position === 'advanced' ? 'normal' : $position ) === $pos_key ); ?>>
									<span>
										<strong><?php echo esc_html( $pos_label ); ?></strong>
										<small><?php echo esc_html( Config::positionEditorNotes()[ $pos_key ] ?? '' ); ?></small>
									</span>
								</label>
							<?php endforeach; ?>
						</div>
					</div>
					<div class="cf-sidebar-control cf-style-row"<?php echo $loc_screen === 'post' ? '' : ' hidden'; ?>>
						<label for="cf-style"><?php esc_html_e( 'Panel style', 'wppowersuite-lite' ); ?></label>
						<select id="cf-style" name="style">
							<?php foreach ( Config::metaBoxStyles() as $style_key => $style_label ) : ?>
								<option value="<?php echo esc_attr( $style_key ); ?>" <?php selected( $style, $style_key ); ?>><?php echo esc_html( $style_label ); ?></option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="cf-sidebar-control cf-priority-row"<?php echo $loc_screen === 'post' ? '' : ' hidden'; ?>>
						<label for="cf-priority"><?php esc_html_e( 'Group order', 'wppowersuite-lite' ); ?></label>
						<select id="cf-priority" name="priority">
							<?php foreach ( Config::priorities() as $pri_key => $pri_label ) : ?>
								<option value="<?php echo esc_attr( $pri_key ); ?>" <?php selected( $priority, $pri_key ); ?>><?php echo esc_html( $pri_label ); ?></option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="cf-sidebar-control">
						<label class="cf-check-label">
							<input type="checkbox" name="show_in_rest" value="1" <?php checked( $show_in_rest ); ?>>
							<?php esc_html_e( 'Show in REST API', 'wppowersuite-lite' ); ?>
						</label>
						<p class="description"><?php esc_html_e( 'Expose this group to blocks and API clients that can edit the matching object.', 'wppowersuite-lite' ); ?></p>
					</div>
				</div>

				<?php if ( $is_edit && $key !== '' ) : ?>
					<?php
					$usage_php       = "<?php echo esc_html( wps_cf_get_field( '" . $key . "', '" . $usage_sample_key . "' ) ); ?>";
					$usage_shortcode = '[wpps_cf group="' . $key . '" field="' . $usage_sample_key . '"]';
					$usage_dynamic   = '{wp_powersuite_cf:' . $key . ':' . $usage_sample_key . '}';
					$cf_usage_snippet = static function ( string $label, string $code ): void {
						?>
						<div class="cf-usage-snippet">
							<div class="cf-usage-snippet__head">
								<span class="cf-usage-snippet__label"><?php echo esc_html( $label ); ?></span>
								<button type="button" class="button button-small cf-usage-copy" data-copy="<?php echo esc_attr( $code ); ?>">
									<span class="dashicons dashicons-clipboard" aria-hidden="true"></span>
									<?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?>
								</button>
							</div>
							<code class="cf-usage-snippet__code"><?php echo esc_html( $code ); ?></code>
						</div>
						<?php
					};
					?>
					<details class="cf-settings cf-settings--usage">
						<summary>
							<span class="dashicons dashicons-editor-code" aria-hidden="true"></span>
							<?php esc_html_e( 'Usage', 'wppowersuite-lite' ); ?>
						</summary>
						<div class="cf-settings__inner">
							<p class="description"><?php esc_html_e( 'Use the group key and field keys in your theme, blocks, or page builders.', 'wppowersuite-lite' ); ?></p>

							<div class="cf-usage-grid">
								<div class="cf-usage-block">
								<h3 class="cf-usage-block__title"><?php esc_html_e( 'Group key', 'wppowersuite-lite' ); ?></h3>
								<div class="cf-usage-snippet cf-usage-snippet--inline">
									<code class="cf-usage-snippet__code"><?php echo esc_html( $key ); ?></code>
									<button type="button" class="button button-small cf-usage-copy" data-copy="<?php echo esc_attr( $key ); ?>">
										<span class="dashicons dashicons-clipboard" aria-hidden="true"></span>
										<?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?>
									</button>
								</div>
							</div>

							<?php if ( $usage_fields !== [] ) : ?>
								<div class="cf-usage-block">
									<h3 class="cf-usage-block__title"><?php esc_html_e( 'Fields', 'wppowersuite-lite' ); ?></h3>
									<table class="widefat striped cf-usage-fields">
										<thead>
											<tr>
												<th scope="col"><?php esc_html_e( 'Label', 'wppowersuite-lite' ); ?></th>
												<th scope="col"><?php esc_html_e( 'Field key', 'wppowersuite-lite' ); ?></th>
												<th scope="col" class="cf-usage-fields__action"><?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?></th>
											</tr>
										</thead>
										<tbody>
											<?php foreach ( $usage_fields as $usage_field ) : ?>
												<tr>
													<td><?php echo esc_html( $usage_field['label'] ); ?></td>
													<td><code><?php echo esc_html( $usage_field['key'] ); ?></code></td>
													<td class="cf-usage-fields__action">
														<?php /* translators: %s: string value. */ ?>
														<button type="button" class="button button-small cf-usage-copy" data-copy="<?php echo esc_attr( $usage_field['key'] ); ?>" aria-label="<?php echo esc_attr( sprintf( __( 'Copy field key %s', 'wppowersuite-lite' ), $usage_field['key'] ) ); ?>">
															<span class="dashicons dashicons-clipboard" aria-hidden="true"></span>
														</button>
													</td>
												</tr>
											<?php endforeach; ?>
										</tbody>
									</table>
								</div>

								<div class="cf-usage-block">
									<h3 class="cf-usage-block__title"><?php esc_html_e( 'Code examples', 'wppowersuite-lite' ); ?></h3>
									<p class="description cf-usage-block__intro"><?php esc_html_e( 'Examples use your first field key. Replace it with any key from the table above.', 'wppowersuite-lite' ); ?></p>
									<?php
									$cf_usage_snippet( __( 'PHP template', 'wppowersuite-lite' ), $usage_php );
									$cf_usage_snippet( __( 'Shortcode', 'wppowersuite-lite' ), $usage_shortcode );
									$cf_usage_snippet( __( 'Dynamic tag', 'wppowersuite-lite' ), $usage_dynamic );
									?>
								</div>
							<?php else : ?>
								<div class="cf-usage-empty">
									<p><?php esc_html_e( 'Add at least one field that saves data to see field keys and code examples here.', 'wppowersuite-lite' ); ?></p>
								</div>
							<?php endif; ?>

							<div class="cf-usage-block">
								<h3 class="cf-usage-block__title"><?php esc_html_e( 'Visual editors', 'wppowersuite-lite' ); ?></h3>
								<ul class="cf-usage-integrations">
									<li>
										<span class="cf-usage-integrations__name"><?php esc_html_e( 'Block editor', 'wppowersuite-lite' ); ?></span>
										<span class="cf-usage-integrations__detail"><?php esc_html_e( 'Insert the “PowerSuite Custom Field” block and choose this group.', 'wppowersuite-lite' ); ?></span>
									</li>
									<li>
										<span class="cf-usage-integrations__name"><?php esc_html_e( 'Page builders', 'wppowersuite-lite' ); ?></span>
										<span class="cf-usage-integrations__detail"><?php esc_html_e( 'Look for the “WP PowerSuite Fields” element or dynamic tag.', 'wppowersuite-lite' ); ?></span>
									</li>
								</ul>
							</div>
						</div>
						</div>
					</details>
				<?php endif; ?>
			</aside>
		</div>
	</form>

	<template id="cf-field-row-template">
		<?php cf_render_field_row_template( $post_types, $taxonomies, $field_targets, $clone_targets, $taxonomy_terms ); ?>
	</template>
	<template id="cf-rule-value-choices" data-wpps-json="1"><?php echo wp_json_encode( $rule_value_choices ); ?></template>
</div>

