<?php
/**
 * EasySite Visual Page Builder – drag-and-drop sections, no HTML required.
 *
 * @package EasySite_Pro
 */

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

define( 'EASYSITE_BUILDER_META', '_easysite_builder_layout' );
define( 'EASYSITE_BUILDER_ENABLED', '_easysite_use_builder' );

/**
 * Registered section types and their simple fields.
 *
 * @return array
 */
function easysite_builder_section_registry() {
	$sections = array(
		'hero' => array(
			'label'       => __( 'Hero Banner', 'easysite-pro' ),
			'description' => __( 'Big headline area at the top of your page.', 'easysite-pro' ),
			'icon'        => 'dashicons-cover-image',
			'fields'      => array(
				'title'       => array( 'type' => 'text', 'label' => __( 'Headline', 'easysite-pro' ), 'placeholder' => __( 'Welcome to our business', 'easysite-pro' ) ),
				'subtitle'    => array( 'type' => 'textarea', 'label' => __( 'Subheadline', 'easysite-pro' ) ),
				'button_text' => array( 'type' => 'text', 'label' => __( 'Button text', 'easysite-pro' ) ),
				'button_url'  => array( 'type' => 'url', 'label' => __( 'Button link', 'easysite-pro' ) ),
				'bg_image'    => array( 'type' => 'image', 'label' => __( 'Background image', 'easysite-pro' ) ),
				'gradient'    => array( 'type' => 'select', 'label' => __( 'Gradient colors', 'easysite-pro' ), 'options' => easysite_gradient_select_options() ),
				'style'       => array( 'type' => 'select', 'label' => __( 'Style', 'easysite-pro' ), 'options' => array(
					'centered'         => __( 'Centered', 'easysite-pro' ),
					'left'             => __( 'Text left', 'easysite-pro' ),
					'overlay-dark'     => __( 'Dark overlay', 'easysite-pro' ),
					'gradient-bg'      => __( 'Full gradient background', 'easysite-pro' ),
					'gradient-overlay' => __( 'Image + gradient overlay', 'easysite-pro' ),
				) ),
			),
		),
		'text' => array(
			'label'       => __( 'Text Block', 'easysite-pro' ),
			'description' => __( 'A simple heading and paragraph. Just type—no HTML.', 'easysite-pro' ),
			'icon'        => 'dashicons-editor-paragraph',
			'fields'      => array(
				'title'   => array( 'type' => 'text', 'label' => __( 'Heading', 'easysite-pro' ) ),
				'content' => array( 'type' => 'textarea', 'label' => __( 'Text', 'easysite-pro' ) ),
				'align'   => array( 'type' => 'select', 'label' => __( 'Alignment', 'easysite-pro' ), 'options' => array( 'left' => __( 'Left', 'easysite-pro' ), 'center' => __( 'Center', 'easysite-pro' ) ) ),
				'gradient'=> array( 'type' => 'select', 'label' => __( 'Background gradient (optional)', 'easysite-pro' ), 'options' => easysite_gradient_select_options() ),
			),
		),
		'image_text' => array(
			'label'       => __( 'Image + Text', 'easysite-pro' ),
			'description' => __( 'Photo beside your message.', 'easysite-pro' ),
			'icon'        => 'dashicons-format-gallery',
			'fields'      => array(
				'title'    => array( 'type' => 'text', 'label' => __( 'Heading', 'easysite-pro' ) ),
				'content'  => array( 'type' => 'textarea', 'label' => __( 'Text', 'easysite-pro' ) ),
				'image'    => array( 'type' => 'image', 'label' => __( 'Image', 'easysite-pro' ) ),
				'layout'   => array( 'type' => 'select', 'label' => __( 'Image position', 'easysite-pro' ), 'options' => array( 'left' => __( 'Image left', 'easysite-pro' ), 'right' => __( 'Image right', 'easysite-pro' ) ) ),
				'btn_text' => array( 'type' => 'text', 'label' => __( 'Button text (optional)', 'easysite-pro' ) ),
				'btn_url'  => array( 'type' => 'url', 'label' => __( 'Button link', 'easysite-pro' ) ),
			),
		),
		'services' => array(
			'label'       => __( 'Services Grid', 'easysite-pro' ),
			'description' => __( 'Show what you offer in neat cards.', 'easysite-pro' ),
			'icon'        => 'dashicons-grid-view',
			'fields'      => array(
				'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
				'item1_title' => array( 'type' => 'text', 'label' => __( 'Service 1 title', 'easysite-pro' ) ),
				'item1_text'  => array( 'type' => 'textarea', 'label' => __( 'Service 1 description', 'easysite-pro' ) ),
				'item1_price' => array( 'type' => 'text', 'label' => __( 'Service 1 price (optional)', 'easysite-pro' ) ),
				'item2_title' => array( 'type' => 'text', 'label' => __( 'Service 2 title', 'easysite-pro' ) ),
				'item2_text'  => array( 'type' => 'textarea', 'label' => __( 'Service 2 description', 'easysite-pro' ) ),
				'item2_price' => array( 'type' => 'text', 'label' => __( 'Service 2 price (optional)', 'easysite-pro' ) ),
				'item3_title' => array( 'type' => 'text', 'label' => __( 'Service 3 title', 'easysite-pro' ) ),
				'item3_text'  => array( 'type' => 'textarea', 'label' => __( 'Service 3 description', 'easysite-pro' ) ),
				'item3_price' => array( 'type' => 'text', 'label' => __( 'Service 3 price (optional)', 'easysite-pro' ) ),
			),
		),
		'testimonials' => array(
			'label'       => __( 'Testimonials', 'easysite-pro' ),
			'description' => __( 'Customer quotes that build trust.', 'easysite-pro' ),
			'icon'        => 'dashicons-format-quote',
			'fields'      => array(
				'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
				'q1'    => array( 'type' => 'textarea', 'label' => __( 'Quote 1', 'easysite-pro' ) ),
				'n1'    => array( 'type' => 'text', 'label' => __( 'Name 1', 'easysite-pro' ) ),
				'r1'    => array( 'type' => 'text', 'label' => __( 'Role 1', 'easysite-pro' ) ),
				'q2'    => array( 'type' => 'textarea', 'label' => __( 'Quote 2', 'easysite-pro' ) ),
				'n2'    => array( 'type' => 'text', 'label' => __( 'Name 2', 'easysite-pro' ) ),
				'r2'    => array( 'type' => 'text', 'label' => __( 'Role 2', 'easysite-pro' ) ),
			),
		),
		'pricing' => array(
			'label'       => __( 'Pricing Table', 'easysite-pro' ),
			'description' => __( 'Simple plans with prices.', 'easysite-pro' ),
			'icon'        => 'dashicons-tag',
			'fields'      => array(
				'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
				'p1_name'  => array( 'type' => 'text', 'label' => __( 'Plan 1 name', 'easysite-pro' ) ),
				'p1_price' => array( 'type' => 'text', 'label' => __( 'Plan 1 price', 'easysite-pro' ) ),
				'p1_desc'  => array( 'type' => 'textarea', 'label' => __( 'Plan 1 description', 'easysite-pro' ) ),
				'p2_name'  => array( 'type' => 'text', 'label' => __( 'Plan 2 name', 'easysite-pro' ) ),
				'p2_price' => array( 'type' => 'text', 'label' => __( 'Plan 2 price', 'easysite-pro' ) ),
				'p2_desc'  => array( 'type' => 'textarea', 'label' => __( 'Plan 2 description', 'easysite-pro' ) ),
				'p3_name'  => array( 'type' => 'text', 'label' => __( 'Plan 3 name', 'easysite-pro' ) ),
				'p3_price' => array( 'type' => 'text', 'label' => __( 'Plan 3 price', 'easysite-pro' ) ),
				'p3_desc'  => array( 'type' => 'textarea', 'label' => __( 'Plan 3 description', 'easysite-pro' ) ),
			),
		),
		'cta' => array(
			'label'       => __( 'Call to Action', 'easysite-pro' ),
			'description' => __( 'Encourage visitors to take the next step.', 'easysite-pro' ),
			'icon'        => 'dashicons-megaphone',
			'fields'      => array(
				'title'       => array( 'type' => 'text', 'label' => __( 'Headline', 'easysite-pro' ) ),
				'subtitle'    => array( 'type' => 'textarea', 'label' => __( 'Supporting text', 'easysite-pro' ) ),
				'button_text' => array( 'type' => 'text', 'label' => __( 'Button text', 'easysite-pro' ) ),
				'button_url'  => array( 'type' => 'url', 'label' => __( 'Button link', 'easysite-pro' ) ),
				'style'       => array( 'type' => 'select', 'label' => __( 'Background', 'easysite-pro' ), 'options' => array(
					'gradient' => __( 'Brand gradient', 'easysite-pro' ),
					'dark'     => __( 'Dark', 'easysite-pro' ),
					'light'    => __( 'Light', 'easysite-pro' ),
				) ),
				'gradient'    => array( 'type' => 'select', 'label' => __( 'Gradient colors', 'easysite-pro' ), 'options' => easysite_gradient_select_options() ),
			),
		),
		'contact' => array(
			'label'       => __( 'Contact Form', 'easysite-pro' ),
			'description' => __( 'Let visitors send you a message.', 'easysite-pro' ),
			'icon'        => 'dashicons-email',
			'fields'      => array(
				'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
				'text'  => array( 'type' => 'textarea', 'label' => __( 'Intro text', 'easysite-pro' ) ),
			),
		),
		'spacer' => array(
			'label'       => __( 'Spacer', 'easysite-pro' ),
			'description' => __( 'Add breathing room between sections.', 'easysite-pro' ),
			'icon'        => 'dashicons-minus',
			'fields'      => array(
				'size' => array( 'type' => 'select', 'label' => __( 'Size', 'easysite-pro' ), 'options' => array( 'small' => __( 'Small', 'easysite-pro' ), 'medium' => __( 'Medium', 'easysite-pro' ), 'large' => __( 'Large', 'easysite-pro' ) ) ),
			),
		),
	);

	if ( easysite_is_bundle() ) {
		$bundle_sections = array(
			'faq' => array(
				'label'       => __( 'FAQ', 'easysite-pro' ),
				'description' => __( 'Answer common questions.', 'easysite-pro' ),
				'icon'        => 'dashicons-editor-help',
				'bundle'      => true,
				'fields'      => array(
					'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
					'q1' => array( 'type' => 'text', 'label' => __( 'Question 1', 'easysite-pro' ) ),
					'a1' => array( 'type' => 'textarea', 'label' => __( 'Answer 1', 'easysite-pro' ) ),
					'q2' => array( 'type' => 'text', 'label' => __( 'Question 2', 'easysite-pro' ) ),
					'a2' => array( 'type' => 'textarea', 'label' => __( 'Answer 2', 'easysite-pro' ) ),
					'q3' => array( 'type' => 'text', 'label' => __( 'Question 3', 'easysite-pro' ) ),
					'a3' => array( 'type' => 'textarea', 'label' => __( 'Answer 3', 'easysite-pro' ) ),
				),
			),
			'team' => array(
				'label'       => __( 'Team', 'easysite-pro' ),
				'description' => __( 'Introduce your team members.', 'easysite-pro' ),
				'icon'        => 'dashicons-groups',
				'bundle'      => true,
				'fields'      => array(
					'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
					'm1_name' => array( 'type' => 'text', 'label' => __( 'Member 1 name', 'easysite-pro' ) ),
					'm1_role' => array( 'type' => 'text', 'label' => __( 'Member 1 role', 'easysite-pro' ) ),
					'm1_img'  => array( 'type' => 'image', 'label' => __( 'Member 1 photo', 'easysite-pro' ) ),
					'm2_name' => array( 'type' => 'text', 'label' => __( 'Member 2 name', 'easysite-pro' ) ),
					'm2_role' => array( 'type' => 'text', 'label' => __( 'Member 2 role', 'easysite-pro' ) ),
					'm2_img'  => array( 'type' => 'image', 'label' => __( 'Member 2 photo', 'easysite-pro' ) ),
					'm3_name' => array( 'type' => 'text', 'label' => __( 'Member 3 name', 'easysite-pro' ) ),
					'm3_role' => array( 'type' => 'text', 'label' => __( 'Member 3 role', 'easysite-pro' ) ),
					'm3_img'  => array( 'type' => 'image', 'label' => __( 'Member 3 photo', 'easysite-pro' ) ),
				),
			),
			'stats' => array(
				'label'       => __( 'Stats / Numbers', 'easysite-pro' ),
				'description' => __( 'Impressive numbers about your business.', 'easysite-pro' ),
				'icon'        => 'dashicons-chart-bar',
				'bundle'      => true,
				'fields'      => array(
					'n1_num'  => array( 'type' => 'text', 'label' => __( 'Stat 1 number', 'easysite-pro' ) ),
					'n1_label'=> array( 'type' => 'text', 'label' => __( 'Stat 1 label', 'easysite-pro' ) ),
					'n2_num'  => array( 'type' => 'text', 'label' => __( 'Stat 2 number', 'easysite-pro' ) ),
					'n2_label'=> array( 'type' => 'text', 'label' => __( 'Stat 2 label', 'easysite-pro' ) ),
					'n3_num'  => array( 'type' => 'text', 'label' => __( 'Stat 3 number', 'easysite-pro' ) ),
					'n3_label'=> array( 'type' => 'text', 'label' => __( 'Stat 3 label', 'easysite-pro' ) ),
					'n4_num'  => array( 'type' => 'text', 'label' => __( 'Stat 4 number', 'easysite-pro' ) ),
					'n4_label'=> array( 'type' => 'text', 'label' => __( 'Stat 4 label', 'easysite-pro' ) ),
				),
			),
			'gallery' => array(
				'label'       => __( 'Image Gallery', 'easysite-pro' ),
				'description' => __( 'Showcase photos in a grid.', 'easysite-pro' ),
				'icon'        => 'dashicons-images-alt2',
				'bundle'      => true,
				'fields'      => array(
					'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
					'img1'  => array( 'type' => 'image', 'label' => __( 'Image 1', 'easysite-pro' ) ),
					'img2'  => array( 'type' => 'image', 'label' => __( 'Image 2', 'easysite-pro' ) ),
					'img3'  => array( 'type' => 'image', 'label' => __( 'Image 3', 'easysite-pro' ) ),
					'img4'  => array( 'type' => 'image', 'label' => __( 'Image 4', 'easysite-pro' ) ),
				),
			),
			'video' => array(
				'label'       => __( 'Video', 'easysite-pro' ),
				'description' => __( 'Embed a YouTube or Vimeo video.', 'easysite-pro' ),
				'icon'        => 'dashicons-video-alt3',
				'bundle'      => true,
				'fields'      => array(
					'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
					'url'   => array( 'type' => 'url', 'label' => __( 'Video URL (YouTube/Vimeo)', 'easysite-pro' ) ),
					'text'  => array( 'type' => 'textarea', 'label' => __( 'Description', 'easysite-pro' ) ),
				),
			),
			'columns' => array(
				'label'       => __( 'Two Columns', 'easysite-pro' ),
				'description' => __( 'Side-by-side text blocks.', 'easysite-pro' ),
				'icon'        => 'dashicons-columns',
				'bundle'      => true,
				'fields'      => array(
					'left_title'  => array( 'type' => 'text', 'label' => __( 'Left heading', 'easysite-pro' ) ),
					'left_text'   => array( 'type' => 'textarea', 'label' => __( 'Left text', 'easysite-pro' ) ),
					'right_title' => array( 'type' => 'text', 'label' => __( 'Right heading', 'easysite-pro' ) ),
					'right_text'  => array( 'type' => 'textarea', 'label' => __( 'Right text', 'easysite-pro' ) ),
				),
			),
			'booking' => array(
				'label'       => __( 'Booking Form', 'easysite-pro' ),
				'description' => __( 'Appointment request form.', 'easysite-pro' ),
				'icon'        => 'dashicons-calendar-alt',
				'bundle'      => true,
				'fields'      => array(
					'title' => array( 'type' => 'text', 'label' => __( 'Section title', 'easysite-pro' ) ),
					'text'  => array( 'type' => 'textarea', 'label' => __( 'Intro text', 'easysite-pro' ) ),
				),
			),
		);
		$sections = array_merge( $sections, $bundle_sections );
	}

	return apply_filters( 'easysite_builder_sections', $sections );
}

/**
 * Default field values for a section type.
 *
 * @param string $type Section type.
 * @return array
 */
function easysite_builder_default_fields( $type ) {
	$registry = easysite_builder_section_registry();
	if ( ! isset( $registry[ $type ] ) ) {
		return array();
	}
	$defaults = array();
	foreach ( $registry[ $type ]['fields'] as $key => $field ) {
		$defaults[ $key ] = '';
	}
	return $defaults;
}

/**
 * Get layout for a post.
 *
 * @param int $post_id Post ID.
 * @return array
 */
function easysite_get_builder_layout( $post_id = 0 ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	$raw     = get_post_meta( $post_id, EASYSITE_BUILDER_META, true );
	if ( empty( $raw ) ) {
		$layout = array();
		return apply_filters( 'easysite_get_builder_layout_filter', $layout, $post_id );
	}
	$layout = json_decode( $raw, true );
	return is_array( $layout ) ? $layout : array();
}

/**
 * Is builder enabled for post?
 *
 * @param int $post_id Post ID.
 * @return bool
 */
function easysite_page_uses_builder( $post_id = 0 ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	return (bool) get_post_meta( $post_id, EASYSITE_BUILDER_ENABLED, true );
}

/**
 * Register builder meta box on pages.
 */
function easysite_builder_meta_box() {
	add_meta_box(
		'easysite_page_builder',
		__( 'EasySite Visual Page Builder', 'easysite-pro' ),
		'easysite_render_builder_meta_box',
		'page',
		'normal',
		'high'
	);
}
add_action( 'add_meta_boxes', 'easysite_builder_meta_box' );

/**
 * Render builder meta box.
 *
 * @param WP_Post $post Post.
 */
function easysite_render_builder_meta_box( $post ) {
	wp_nonce_field( 'easysite_builder_save', 'easysite_builder_nonce' );
	$enabled = easysite_page_uses_builder( $post->ID );
	$layout  = easysite_get_builder_layout( $post->ID );
	$registry = easysite_builder_section_registry();
	?>
	<div class="easysite-pb-wrap" id="easysite-page-builder"
		data-registry="<?php echo esc_attr( wp_json_encode( $registry ) ); ?>"
		data-layout="<?php echo esc_attr( wp_json_encode( $layout ) ); ?>">

		<p class="easysite-pb-intro">
			<?php esc_html_e( 'Build beautiful pages by dragging sections and typing in plain boxes—no HTML needed.', 'easysite-pro' ); ?>
		</p>

		<p>
			<label class="easysite-pb-toggle">
				<input type="checkbox" name="easysite_use_builder" value="1" <?php checked( $enabled ); ?> />
				<strong><?php esc_html_e( 'Use EasySite Visual Builder for this page', 'easysite-pro' ); ?></strong>
			</label>
		</p>

		<div class="easysite-pb-ui <?php echo $enabled ? '' : 'is-disabled'; ?>">
			<aside class="easysite-pb-sidebar">
				<h3><?php esc_html_e( 'Add a section', 'easysite-pro' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Click or drag onto your page.', 'easysite-pro' ); ?></p>
				<ul class="easysite-pb-library">
					<?php foreach ( $registry as $type => $section ) : ?>
						<li>
							<button type="button" class="easysite-pb-add-section" data-type="<?php echo esc_attr( $type ); ?>">
								<span class="dashicons <?php echo esc_attr( $section['icon'] ); ?>"></span>
								<?php echo esc_html( $section['label'] ); ?>
							</button>
						</li>
					<?php endforeach; ?>
				</ul>
			</aside>

			<div class="easysite-pb-canvas-wrap">
				<h3><?php esc_html_e( 'Your page layout', 'easysite-pro' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Drag sections to reorder. Click a section to edit its text and images.', 'easysite-pro' ); ?></p>
				<ul class="easysite-pb-canvas" id="easysite-pb-canvas"></ul>
				<p class="easysite-pb-empty"><?php esc_html_e( 'No sections yet. Add one from the left panel.', 'easysite-pro' ); ?></p>
			</div>
		</div>

		<input type="hidden" name="easysite_builder_layout" id="easysite-builder-layout" value="<?php echo esc_attr( wp_json_encode( $layout ) ); ?>" />
	</div>
	<?php
}

/**
 * Save builder data.
 *
 * @param int $post_id Post ID.
 */
function easysite_save_builder_meta( $post_id ) {
	if ( ! isset( $_POST['easysite_builder_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['easysite_builder_nonce'] ) ), 'easysite_builder_save' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$use = ! empty( $_POST['easysite_use_builder'] );
	update_post_meta( $post_id, EASYSITE_BUILDER_ENABLED, $use ? '1' : '' );

	if ( isset( $_POST['easysite_builder_layout'] ) ) {
		$raw    = wp_unslash( $_POST['easysite_builder_layout'] );
		$layout = json_decode( $raw, true );
		if ( is_array( $layout ) ) {
			$clean = easysite_sanitize_builder_layout( $layout );
			update_post_meta( $post_id, EASYSITE_BUILDER_META, wp_json_encode( $clean ) );
		}
	}
}
add_action( 'save_post_page', 'easysite_save_builder_meta' );

/**
 * Sanitize builder layout array.
 *
 * @param array $layout Layout.
 * @return array
 */
function easysite_sanitize_builder_layout( $layout ) {
	$registry = easysite_builder_section_registry();
	$clean    = array();

	foreach ( $layout as $block ) {
		if ( empty( $block['type'] ) || ! isset( $registry[ $block['type'] ] ) ) {
			continue;
		}
		$type   = sanitize_key( $block['type'] );
		$fields = array();
		$defs   = $registry[ $type ]['fields'];

		if ( ! empty( $block['fields'] ) && is_array( $block['fields'] ) ) {
			foreach ( $defs as $key => $field ) {
				if ( ! isset( $block['fields'][ $key ] ) ) {
					continue;
				}
				$val = $block['fields'][ $key ];
				if ( 'image' === $field['type'] || 'url' === $field['type'] ) {
					$fields[ $key ] = esc_url_raw( $val );
				} elseif ( 'textarea' === $field['type'] ) {
					$fields[ $key ] = easysite_sanitize_richtext( $val );
				} else {
					$fields[ $key ] = sanitize_text_field( $val );
				}
			}
		}

		$clean[] = array(
			'id'     => ! empty( $block['id'] ) ? sanitize_key( $block['id'] ) : uniqid( 'esb_', true ),
			'type'   => $type,
			'fields' => $fields,
			'design' => easysite_sanitize_block_design( $block['design'] ?? array() ),
		);
	}

	return $clean;
}

/**
 * Enqueue builder admin assets.
 *
 * @param string $hook Hook.
 */
function easysite_builder_admin_assets( $hook ) {
	if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
		return;
	}
	$screen = get_current_screen();
	if ( ! $screen || 'page' !== $screen->post_type ) {
		return;
	}

	wp_enqueue_media();
	wp_enqueue_script( 'jquery-ui-sortable' );
	wp_enqueue_style(
		'easysite-page-builder-admin',
		EASYSITE_PRO_URI . '/assets/css/page-builder-admin.css',
		array( 'easysite-pro-admin' ),
		EASYSITE_PRO_VERSION
	);
	wp_enqueue_script(
		'easysite-page-builder',
		EASYSITE_PRO_URI . '/assets/js/page-builder.js',
		array( 'jquery', 'jquery-ui-sortable', 'easysite-pro-admin' ),
		EASYSITE_PRO_VERSION,
		true
	);

	wp_localize_script( 'easysite-page-builder', 'easysitePageBuilder', array(
		'i18n' => array(
			'remove'    => __( 'Remove section', 'easysite-pro' ),
			'edit'      => __( 'Edit section', 'easysite-pro' ),
			'collapse'  => __( 'Collapse', 'easysite-pro' ),
			'selectImg' => __( 'Select image', 'easysite-pro' ),
			'changeImg' => __( 'Change image', 'easysite-pro' ),
			'aiSuggest' => __( 'Suggest text', 'easysite-pro' ),
		),
	) );
}
add_action( 'admin_enqueue_scripts', 'easysite_builder_admin_assets', 20 );

/**
 * Enqueue frontend builder styles.
 */
function easysite_builder_front_assets() {
	if ( ! is_singular( 'page' ) || ! easysite_page_uses_builder() ) {
		return;
	}
	wp_enqueue_style(
		'easysite-page-builder',
		EASYSITE_PRO_URI . '/assets/css/page-builder.css',
		array( 'easysite-pro-main' ),
		EASYSITE_PRO_VERSION
	);
	if ( easysite_get_mod( 'easysite_animations', true ) ) {
		wp_enqueue_style(
			'easysite-animations',
			EASYSITE_PRO_URI . '/assets/css/animations.css',
			array( 'easysite-page-builder' ),
			EASYSITE_PRO_VERSION
		);
	}
}
add_action( 'wp_enqueue_scripts', 'easysite_builder_front_assets', 25 );

/**
 * Render full page builder output.
 *
 * @param int $post_id Post ID.
 */
function easysite_render_page_builder( $post_id = 0 ) {
	$layout = easysite_get_builder_layout( $post_id );
	if ( empty( $layout ) ) {
		echo '<p class="easysite-pb-notice">' . esc_html__( 'This page uses the EasySite Builder but has no sections yet. Edit the page to add content.', 'easysite-pro' ) . '</p>';
		return;
	}

	$animate = easysite_get_mod( 'easysite_animations', true );
	echo '<div class="easysite-pb-page">';
	foreach ( $layout as $index => $block ) {
		$type = $block['type'] ?? '';
		$data = $block['fields'] ?? array();
		$fn   = 'easysite_pb_render_' . str_replace( '-', '_', $type );
		if ( function_exists( $fn ) ) {
			if ( empty( $block['id'] ) ) {
				$block['id'] = 'esb_' . $index;
			}
			$GLOBALS['easysite_pb_current_block'] = $block;
			$classes = 'easysite-pb-block easysite-pb-' . sanitize_html_class( $type );
			if ( $animate ) {
				$classes .= ' easysite-animate';
			}
			echo '<div class="' . esc_attr( $classes ) . '"';
			echo ' data-block-id="' . esc_attr( $block['id'] ) . '"';
			echo ' data-block-index="' . esc_attr( (string) $index ) . '"';
			echo ' data-block-type="' . esc_attr( $type ) . '"';
			echo easysite_block_design_attrs( $block ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo '>';
			call_user_func( $fn, $data );
			echo '</div>';
		}
	}
	echo '</div>';
}

/**
 * Get field with fallback.
 *
 * @param array  $data Data.
 * @param string $key  Key.
 * @param string $default Default.
 * @return string
 */
function easysite_pb_field( $data, $key, $default = '' ) {
	return isset( $data[ $key ] ) && '' !== $data[ $key ] ? $data[ $key ] : $default;
}

/**
 * Render image URL or placeholder.
 *
 * @param array  $data Data.
 * @param string $key  Field key.
 * @param string $placeholder Placeholder type.
 * @return string
 */
function easysite_pb_image( $data, $key, $placeholder = 'hero' ) {
	$url = easysite_pb_field( $data, $key );
	return $url ? $url : easysite_placeholder_image( $placeholder );
}

// Load section renderers.
require_once EASYSITE_PRO_DIR . '/inc/page-builder-render.php';

/**
 * Add admin menu link for builder help.
 */
function easysite_builder_submenu() {
	add_submenu_page(
		'easysite-setup',
		__( 'Page Builder Guide', 'easysite-pro' ),
		__( 'Page Builder', 'easysite-pro' ),
		'edit_pages',
		'easysite-builder-help',
		'easysite_builder_help_page'
	);
}
add_action( 'admin_menu', 'easysite_builder_submenu', 20 );

/**
 * Builder help admin page.
 */
function easysite_builder_help_page() {
	?>
	<div class="wrap easysite-help">
		<h1><?php esc_html_e( 'EasySite Visual Page Builder', 'easysite-pro' ); ?></h1>
		<p><?php esc_html_e( 'Edit any page, enable "Use EasySite Visual Builder", then drag sections and type your text. No coding required.', 'easysite-pro' ); ?></p>
		<ol>
			<li><?php esc_html_e( 'Pages → Add New (or edit an existing page)', 'easysite-pro' ); ?></li>
			<li><?php esc_html_e( 'Check "Use EasySite Visual Builder for this page"', 'easysite-pro' ); ?></li>
			<li><?php esc_html_e( 'Click sections on the left to add them', 'easysite-pro' ); ?></li>
			<li><?php esc_html_e( 'Drag sections to reorder', 'easysite-pro' ); ?></li>
			<li><?php esc_html_e( 'Fill in the boxes—headlines, text, images, buttons', 'easysite-pro' ); ?></li>
			<li><?php esc_html_e( 'Click Update to publish', 'easysite-pro' ); ?></li>
		</ol>
	</div>
	<?php
}

/**
 * Starter layout for new pages (filter).
 *
 * @param array $layout Layout.
 * @param int   $post_id Post ID.
 * @return array
 */
function easysite_builder_default_home_layout( $layout, $post_id ) {
	if ( ! empty( $layout ) ) {
		return $layout;
	}
	$template = get_page_template_slug( $post_id );
	if ( 'templates/template-home.php' !== $template && ! is_front_page() ) {
		return $layout;
	}
	return array(
		array( 'id' => 'esb_hero', 'type' => 'hero', 'fields' => array(
			'title' => __( 'Welcome to Our Business', 'easysite-pro' ),
			'subtitle' => __( 'We help you grow with friendly, reliable service.', 'easysite-pro' ),
			'button_text' => __( 'Get Started', 'easysite-pro' ),
			'button_url' => '/contact',
			'style' => 'gradient-overlay',
			'gradient' => 'brand',
		) ),
		array( 'id' => 'esb_about', 'type' => 'image_text', 'fields' => array(
			'title' => __( 'About Us', 'easysite-pro' ),
			'content' => __( 'Tell visitors who you are and why they should trust you. Replace this text with your own story.', 'easysite-pro' ),
			'layout' => 'right',
		) ),
		array( 'id' => 'esb_services', 'type' => 'services', 'fields' => array(
			'title' => __( 'Our Services', 'easysite-pro' ),
			'item1_title' => __( 'Consultation', 'easysite-pro' ),
			'item1_text' => __( 'We listen to your needs and recommend the best approach.', 'easysite-pro' ),
			'item2_title' => __( 'Delivery', 'easysite-pro' ),
			'item2_text' => __( 'Professional work delivered on time, every time.', 'easysite-pro' ),
			'item3_title' => __( 'Support', 'easysite-pro' ),
			'item3_text' => __( 'Friendly help whenever you need it.', 'easysite-pro' ),
		) ),
		array( 'id' => 'esb_cta', 'type' => 'cta', 'fields' => array(
			'title' => __( 'Ready to get started?', 'easysite-pro' ),
			'subtitle' => __( 'Contact us today for a free consultation.', 'easysite-pro' ),
			'button_text' => __( 'Contact Us', 'easysite-pro' ),
			'button_url' => '/contact',
			'style' => 'gradient',
			'gradient' => 'brand',
		) ),
	);
}
add_filter( 'easysite_get_builder_layout_filter', 'easysite_builder_default_home_layout', 10, 2 );
