<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-formatting-render.php
 *
 * Formatting Tab — Render Methods
 *
 * Contains all HTML-output methods for the Formatting settings tab.
 * Extracted from MBS_Tab_Formatting (R-02, 2026-04-25).
 *
 * MBS_Tab_Formatting::render() delegates to:
 *   (new MBS_Tab_Formatting_Render())->render()
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Tab_Formatting_Render { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- mbs_/MBS_ prefix is correct; scanner not configured with plugin prefix
	// ── Public render orchestrator ──────────────────────────────────────────

	public function render(): void {
		$is_pro         = mbs_is_pro();
		$symbol         = MBS_Formatting::get_currency_symbol( get_option( 'mbs_setting_general_currency', 'USD' ) );
		$layouts        = MBS_Layout_Registry::get_layout_options();
		$current_layout = get_option( 'mbs_setting_formatting_default_layout', 'hero' );

		?>
		<div class="mbs-tab-formatting">

			<h2><?php esc_html_e( 'Formatting Settings', 'my-book-showroom' ); ?></h2>
			<p class="mbs-settings-subtitle">
				<?php esc_html_e( 'Control how your books appear on archive and single pages.', 'my-book-showroom' ); ?>
			</p>

			<?php /* ═══════════════ Card 1: Display & Formatting ═══════════════ */ ?>
			<div class="mbs-settings-card">
				<h3><?php esc_html_e( 'Display & Formatting', 'my-book-showroom' ); ?></h3>

				<?php $this->render_layout_field( $layouts, $current_layout, $is_pro ); ?>

				<hr class="mbs-card-divider">

				<?php $this->render_display_fields( $symbol ); ?>
			</div>

			<?php /* ═══════════════ Card 2: Advanced & Sharing ═══════════════ */ ?>
			<div class="mbs-settings-card">
				<h3><?php esc_html_e( 'Advanced & Sharing', 'my-book-showroom' ); ?></h3>

				<?php $this->render_share_text_field( $is_pro ); ?>

				<hr class="mbs-card-divider">

				<?php $this->render_section_order_field(); ?>
			</div>

			<?php /* ═══════════════ Card 3: Book Format Types ═══════════════ */ ?>
			<div class="mbs-settings-card">
				<h3><?php esc_html_e( 'Book Format Types', 'my-book-showroom' ); ?></h3>

				<?php $this->render_format_types_field(); ?>
			</div>

		</div>
		<?php
	}

	// ── Private: sub-render methods ─────────────────────────────────────────

	private function render_layout_field( array $layouts, string $current_layout, bool $is_pro ): void {
		?>
		<div class="mbs-settings-field-cell mbs-formatting-layout-cell">
			<label for="mbs_setting_formatting_default_layout"><?php esc_html_e( 'Default Layout', 'my-book-showroom' ); ?></label>
			<select id="mbs_setting_formatting_default_layout"
			        name="mbs_setting_formatting_default_layout"
			        class="regular-text">
				<?php foreach ( $layouts as $slug => $data ) :
					$label    = is_array( $data ) ? $data['label'] : $data;
					$is_pro_l = is_array( $data ) ? ! empty( $data['pro'] ) : false;
					$suffix   = ( $is_pro_l && ! $is_pro ) ? ' (PRO)' : '';
				?>
					<option value="<?php echo esc_attr( $slug ); ?>" <?php selected( $current_layout, $slug ); ?>>
						<?php echo esc_html( $label . $suffix ); ?>
					</option>
				<?php endforeach; ?>
			</select>

			<div class="mbs-layout-thumbnail-grid" role="radiogroup" aria-label="<?php esc_attr_e( 'Layout preview thumbnails', 'my-book-showroom' ); ?>">
				<?php foreach ( $layouts as $slug => $data ) :
					$label    = is_array( $data ) ? $data['label'] : $data;
					$is_pro_l = is_array( $data ) ? ! empty( $data['pro'] ) : false;
					$disabled = $is_pro_l && ! $is_pro;
					$selected = ( $current_layout === $slug );

					$classes = array( 'mbs-layout-thumbnail', 'mbs-thumb-' . str_replace( '_', '-', $slug ) );
					if ( $selected )  { $classes[] = 'is-selected'; }
					if ( $disabled )  { $classes[] = 'is-disabled'; }
				?>
					<button type="button"
					        class="<?php echo esc_attr( implode( ' ', $classes ) ); ?>"
					        data-layout="<?php echo esc_attr( $slug ); ?>"
					        role="radio"
					        aria-checked="<?php echo $selected ? 'true' : 'false'; ?>"
					        <?php disabled( $disabled, true ); ?>>
						<span class="mbs-layout-thumbnail-canvas" aria-hidden="true">
							<img src="<?php echo esc_url( MBS_ASSETS_URL . 'images/layout-thumbs/' . $slug . '.svg' ); ?>"
							     width="108" height="72" alt="" loading="lazy">
						</span>
						<span class="mbs-layout-thumbnail-label"><?php echo esc_html( $label ); ?></span>
						<?php if ( $is_pro_l && ! $is_pro ) : ?>
							<span class="mbs-layout-thumbnail-badge"><?php esc_html_e( 'PRO', 'my-book-showroom' ); ?></span>
						<?php endif; ?>
					</button>
				<?php endforeach; ?>
			</div>

			<div id="mbs-layout-description"
			     class="mbs-layout-description"
			     aria-live="polite"
			     aria-atomic="true"></div>

			<p class="description">
				<?php if ( $is_pro ) : ?>
					<?php esc_html_e( 'Click a thumbnail to select, or use the dropdown above.', 'my-book-showroom' ); ?>
				<?php else : ?>
					<?php esc_html_e( 'Click a thumbnail to select, or use the dropdown above. PRO layouts require an active PRO license.', 'my-book-showroom' ); ?>
				<?php endif; ?>
			</p>
		</div>
		<?php
	}

	private function render_display_fields( string $symbol ): void {
		// PLG-026: canonical identifiers — stored value is 'symbol_first' or 'symbol_last'.
		// Backward compat: old stored values were sample strings like "$12.99" (first char
		// not a digit → symbol_first) or "12.99$" (first char is a digit → symbol_last).
		// ST-003 fix: canonical values must be matched first; both start with 's' so the
		// first-char heuristic incorrectly normalised 'symbol_last' → 'symbol_first'.
		$raw_price_pref = get_option( 'mbs_setting_formatting_price_format', 'symbol_first' );
		if ( in_array( $raw_price_pref, array( 'symbol_first', 'symbol_last' ), true ) ) {
			$current_price = $raw_price_pref;
		} else {
			// Legacy backward-compat: sample-string heuristic.
			$current_price = ( '' !== $raw_price_pref && ctype_digit( substr( $raw_price_pref, 0, 1 ) ) )
				? 'symbol_last'
				: 'symbol_first';
		}

		$price_formats = array(
			/* translators: %s: currency symbol e.g. "$" */
			'symbol_first' => sprintf( __( 'Symbol first (%s12.99)', 'my-book-showroom' ), $symbol ),
			/* translators: %s: currency symbol e.g. "$" */
			'symbol_last'  => sprintf( __( 'Symbol last (12.99%s)', 'my-book-showroom' ), $symbol ),
		);

		$current_date = get_option( 'mbs_setting_formatting_date_format', 'F j, Y' );
		$date_formats = array(
			'F j, Y' => 'January 15, 2026',
			'Y-m-d'  => '2026-01-15',
			'm/d/Y'  => '01/15/2026',
			'd/m/Y'  => '15/01/2026',
		);
		?>

		<?php /* ── Row 1: Archive Title / Items per Page ──────────────── */ ?>
		<div class="mbs-settings-field-grid">
			<div class="mbs-settings-field-cell">
				<label for="mbs_setting_formatting_archive_title"><?php esc_html_e( 'Archive Page Title', 'my-book-showroom' ); ?></label>
				<input type="text"
				       id="mbs_setting_formatting_archive_title"
				       name="mbs_setting_formatting_archive_title"
				       value="<?php echo esc_attr( mbs_get_setting( 'formatting', 'archive_title', 'pub' === mbs_get_license_tier_label() ? __( 'Our Books', 'my-book-showroom' ) : __( 'My Books', 'my-book-showroom' ) ) ); ?>"
				       class="regular-text">
				<p class="description"><?php esc_html_e( 'Title shown on book archive pages.', 'my-book-showroom' ); ?></p>
			</div>

			<div class="mbs-settings-field-cell">
				<label for="mbs_setting_formatting_items_per_page"><?php esc_html_e( 'Items per Page', 'my-book-showroom' ); ?></label>
				<input type="number"
				       id="mbs_setting_formatting_items_per_page"
				       name="mbs_setting_formatting_items_per_page"
				       value="<?php echo esc_attr( get_option( 'mbs_setting_formatting_items_per_page', 6 ) ); ?>"
				       min="1" max="100"
				       class="small-text">
				<p class="description"><?php esc_html_e( 'Number of books shown per archive page.', 'my-book-showroom' ); ?></p>
			</div>
		</div>

		<?php /* ── Row 2: Price Format / Publication Date Format ──────── */ ?>
		<div class="mbs-settings-field-grid">
			<div class="mbs-settings-field-cell">
				<label for="mbs_setting_formatting_price_format"><?php esc_html_e( 'Price Format', 'my-book-showroom' ); ?></label>
				<select id="mbs_setting_formatting_price_format"
				        name="mbs_setting_formatting_price_format"
				        class="regular-text">
					<?php foreach ( $price_formats as $format => $label ) : ?>
						<option value="<?php echo esc_attr( $format ); ?>" <?php selected( $current_price, $format ); ?>>
							<?php echo esc_html( $label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
				<p class="description"><?php esc_html_e( 'Uses the Default Currency from the General tab.', 'my-book-showroom' ); ?></p>
			</div>

			<div class="mbs-settings-field-cell">
				<label for="mbs_setting_formatting_date_format"><?php esc_html_e( 'Publication Date Format', 'my-book-showroom' ); ?></label>
				<select id="mbs_setting_formatting_date_format"
				        name="mbs_setting_formatting_date_format"
				        class="regular-text">
					<?php foreach ( $date_formats as $format => $example ) : ?>
						<option value="<?php echo esc_attr( $format ); ?>" <?php selected( $current_date, $format ); ?>>
							<?php echo esc_html( $example ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>
		</div>

		<?php /* ── Purchase Link Text (full width) ────────────────────── */ ?>
		<div class="mbs-settings-field-cell">
			<label for="mbs_setting_formatting_purchase_link_text"><?php esc_html_e( 'Purchase Link Text', 'my-book-showroom' ); ?></label>
			<input type="text"
			       id="mbs_setting_formatting_purchase_link_text"
			       name="mbs_setting_formatting_purchase_link_text"
			       value="<?php echo esc_attr( get_option( 'mbs_setting_formatting_purchase_link_text', 'Buy Now' ) ); ?>"
			       class="regular-text"
			       style="max-width: 320px;">
			<p class="description"><?php esc_html_e( 'Text for purchase/buy buttons on book pages.', 'my-book-showroom' ); ?></p>
		</div>
		<?php
	}

	private function render_share_text_field( bool $is_pro ): void {
		?>
		<div class="mbs-settings-field-cell mbs-formatting-share-text-cell">
			<label for="mbs_setting_formatting_share_text">
				<?php esc_html_e( 'Global Share Text', 'my-book-showroom' ); ?>
				<?php if ( ! $is_pro ) : ?>
					<span class="pro-badge"><?php esc_html_e( 'PRO', 'my-book-showroom' ); ?></span>
				<?php endif; ?>
			</label>
			<textarea id="mbs_setting_formatting_share_text"
			          name="mbs_setting_formatting_share_text"
			          rows="4"
			          class="large-text"
			          <?php disabled( ! $is_pro, true ); ?>><?php echo esc_textarea( get_option( 'mbs_setting_formatting_share_text', __( 'Check out "{title}" by {author} — {url}', 'my-book-showroom' ) ) ); ?></textarea>

			<?php if ( $is_pro ) : ?>
				<p class="description mbs-merge-tag-pills-label">
					<?php esc_html_e( 'Available merge tags — click to insert at cursor:', 'my-book-showroom' ); ?>
				</p>
				<div class="mbs-merge-tag-pills" data-target="#mbs_setting_formatting_share_text">
					<button type="button" class="mbs-merge-tag-pill" data-tag="{title}">{title}</button>
					<button type="button" class="mbs-merge-tag-pill" data-tag="{author}">{author}</button>
					<button type="button" class="mbs-merge-tag-pill" data-tag="{url}">{url}</button>
					<button type="button" class="mbs-merge-tag-pill" data-tag="{price}">{price}</button>
					<button type="button" class="mbs-merge-tag-pill" data-tag="{isbn}">{isbn}</button>
				</div>
			<?php else : ?>
				<p class="description">
					<?php esc_html_e( 'Share message template used when visitors share a book. Merge tags ({title}, {author}, {url}, {price}, {isbn}) available with a PRO license.', 'my-book-showroom' ); ?>
				</p>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_section_order_field(): void {
		$admin_rows    = MBS_Section_Order_DAO::get_order_admin( 0 );
		$current_order = empty( $admin_rows )
			? MBS_Section_Helper::get_canonical_keys()
			: array_column( $admin_rows, 'key' );
		// Build global default visibility map (UX-NAV-002-001).
		$visibility_state = array();
		foreach ( $admin_rows as $row ) {
			$visibility_state[ $row['key'] ] = $row['is_visible'];
		}
		$section_data       = MBS_Section_Helper::get_available_section_data();
		$is_pro_user        = mbs_is_pro();
		$available_sections = array_combine(
			array_keys( $section_data ),
			array_column( $section_data, 'label' )
		);
		// BUG-SO-005 fix (UX-EDIT-002 Phase 0-B B4): filter hidden input through
		// $available_sections so stale keys never appear in the submitted value.
		// $available_sections contains all available canonical sections.
		// UX-EDIT-002 Phase 3-A: Merge global-default order with any missing canonical
		// sections so newly-added sections always appear even if the DB seed is stale.
		$filtered_order = array_values( array_filter( $current_order, static function( $s ) use ( $available_sections ) {
			return isset( $available_sections[ $s ] );
		} ) );
		$missing_keys   = array_values( array_diff( array_keys( $available_sections ), $filtered_order ) );
		$rendered_order = array_merge( $filtered_order, $missing_keys );
		$current_order  = $rendered_order; // Use merged order for display loops.
		$order_string   = implode( ',', $rendered_order );
		?>
		<div class="mbs-settings-field-cell mbs-formatting-section-order-cell">
			<span class="mbs-label-tip-pair"><label for="mbs_section_order_input"><?php esc_html_e( 'Section Display Order', 'my-book-showroom' ); ?></label><?php mbs_help_tip(
			__( 'These settings define the global default for every book. The "Show by default" checkbox controls whether a section appears on book pages unless overridden. Authors can override visibility per-book in the book editor (Sections tab). PRO-locked sections follow the same hierarchy but cannot be enabled until you upgrade.', 'my-book-showroom' ),
			__( 'About Section Display Order', 'my-book-showroom' ),
			'mbs-help-tip--wide'
		); ?></span>
			<p class="description">
				<?php esc_html_e( 'Sort and reorder sections. Check the box to show a section by default; uncheck to hide it. Changes save with the form.', 'my-book-showroom' ); ?>
			</p>

			<ul id="mbs-section-sortable" class="mbs-sortable-list">
				<?php foreach ( $current_order as $slug ) : ?>
					<?php if ( isset( $available_sections[ $slug ] ) ) : ?>
						<?php
						$is_pro_section = isset( $section_data[ $slug ] ) && 'pro' === $section_data[ $slug ]['tier'];
						$locked         = ! $is_pro_user && $is_pro_section;
						$locked_class   = $locked ? ' mbs-pro-locked' : '';
						$is_visible     = $visibility_state[ $slug ] ?? true;
						$dimmed_class   = $is_visible ? '' : ' mbs-section-dimmed';
						?>
						<li data-slug="<?php echo esc_attr( $slug ); ?>" class="mbs-sortable-item<?php echo esc_attr( $locked_class . $dimmed_class ); ?>">
							<?php if ( $is_pro_user ) : ?>
							<span class="dashicons dashicons-menu mbs-drag-handle"></span>
							<?php endif; ?>
							<?php if ( $locked ) : ?>
								<span class="dashicons dashicons-lock mbs-pro-lock-icon"></span>
							<?php endif; ?>
							<span class="mbs-sortable-label"><?php echo esc_html( $available_sections[ $slug ] ); ?></span>
							<label class="mbs-section-visibility">
								<input type="checkbox"
								       name="mbs_section_global_visible[<?php echo esc_attr( $slug ); ?>]"
								       value="1"
								       <?php checked( $is_visible, true ); ?>
								       <?php disabled( $locked, true ); ?>>
								<?php esc_html_e( 'Show by default', 'my-book-showroom' ); ?>
							</label>
						</li>
					<?php endif; ?>
				<?php endforeach; ?>
			</ul>

			<details class="mbs-section-order-fallback">
				<summary><?php esc_html_e( 'No JavaScript? Use keyboard arrows instead', 'my-book-showroom' ); ?></summary>
				<table id="mbs-section-order-table" class="mbs-section-order-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Section', 'my-book-showroom' ); ?></th>
							<th><?php esc_html_e( 'Order', 'my-book-showroom' ); ?></th>
							<th><?php esc_html_e( 'Visible', 'my-book-showroom' ); ?></th>
						</tr>
					</thead>
					<tbody id="mbs-section-order-body">
						<?php foreach ( $current_order as $slug ) : ?>
							<?php if ( isset( $available_sections[ $slug ] ) ) : ?>
								<?php
								$is_pro_section = isset( $section_data[ $slug ] ) && 'pro' === $section_data[ $slug ]['tier'];
								$locked         = ! $is_pro_user && $is_pro_section;
								$row_class      = $locked ? ' class="mbs-pro-locked"' : '';
								$is_visible     = $visibility_state[ $slug ] ?? true;
								?>
								<tr data-slug="<?php echo esc_attr( $slug ); ?>"<?php echo $row_class; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded class string ?>>
									<td class="mbs-drag-handle"><span class="dashicons dashicons-menu"></span></td>
									<td>
										<?php if ( $locked ) : ?>
											<span class="dashicons dashicons-lock mbs-pro-lock-icon"></span>
										<?php endif; ?>
										<?php echo esc_html( $available_sections[ $slug ] ); ?>
										<button type="button" class="button button-small mbs-up" title="<?php esc_attr_e( 'Move up', 'my-book-showroom' ); ?>">&#8593;</button>
										<button type="button" class="button button-small mbs-down" title="<?php esc_attr_e( 'Move down', 'my-book-showroom' ); ?>">&#8595;</button>
									</td>
									<td>
										<label class="mbs-section-visibility">
											<input type="checkbox"
											       name="mbs_section_global_visible[<?php echo esc_attr( $slug ); ?>]"
											       value="1"
											       <?php checked( $is_visible, true ); ?>
											       <?php disabled( $locked, true ); ?>>
										</label>
									</td>
								</tr>
							<?php endif; ?>
						<?php endforeach; ?>
					</tbody>
				</table>
			</details>

			<input type="hidden"
			       id="mbs_section_order_input"
			       name="mbs_setting_formatting_section_order"
			       value="<?php echo esc_attr( $order_string ); ?>">

			<p class="mbs-section-order-actions">
				<button type="button" class="button button-secondary mbs-reset-order">
					<?php esc_html_e( 'Reset to Default Order', 'my-book-showroom' ); ?>
				</button>
			</p>
		</div>
		<?php
	}

	private function render_format_types_field(): void {
		$format_options = MBS_Format_Options::get_format_options();

		// Convert stored key→label map to textarea display format.
		$lines = array();
		foreach ( $format_options as $key => $label ) {
			$lines[] = $key . '|' . $label;
		}
		$textarea_value = implode( "\n", $lines );
		?>
		<div class="mbs-settings-field-cell mbs-formatting-format-types-cell">
			<span class="mbs-label-tip-pair"><label for="mbs_setting_format_types">
				<?php esc_html_e( 'Available Format Types', 'my-book-showroom' ); ?>
			</label><?php mbs_help_tip(
				__( 'Each line defines one format type. The key (before the pipe) is stored in the database — it must be lowercase with no spaces (e.g. paperback, large_print). The label (after the pipe) is what authors see in the dropdown. Important: changing a key after books have been saved with that format will orphan those existing format rows, losing their format assignments. Add new types freely; rename or delete keys with caution.', 'my-book-showroom' ),
				__( 'About Format Types', 'my-book-showroom' ),
				'mbs-help-tip--wide'
			); ?></span>
			<textarea id="mbs_setting_format_types"
			          name="mbs_setting_format_types"
			          rows="<?php echo count( $format_options ) + 2; ?>"
			          class="large-text"
			          style="font-family: monospace; max-width: 520px;"><?php echo esc_textarea( $textarea_value ); ?></textarea>
			<p class="description">
				<?php esc_html_e( 'One format type per line in the format: key|Label — for example: paperback|Paperback', 'my-book-showroom' ); ?><br>
				<?php esc_html_e( 'The key must be lowercase with no spaces. Changing a key after books have been saved with that format will orphan those existing format rows.', 'my-book-showroom' ); ?>
			</p>
		</div>
		<?php
	}

}
