<?php
/**
 * File Path: includes/admin/tabs/class-mbs-tab-appearance.php
 *
 * Appearance Tab — Orchestrator
 *
 * Handles settings registration, asset enqueuing, and render dispatch.
 * All section HTML lives in MBS_Tab_Appearance_Render
 * (includes/admin/tabs/class-mbs-tab-appearance-render.php).
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Tab_Appearance {

	/**
	 * FREE color token defaults. Public constant so MBS_Settings::enqueue_assets()
	 * can localize these to child-admin-appearance.js without duplicating values.
	 */
	public const FREE_DEFAULTS = array(
		'accent'      => '#4AABB8',
		'button_bg'   => '#2C3E6B',
		'button_text' => '#FFFFFF',
		'link'        => '#4AABB8',
	);

	public function register(): void {
		// ── FREE tokens (4) ──────────────────────────────────────────────────
		register_setting( 'mbs_appearance', 'mbs_setting_appearance_accent', array(
			'sanitize_callback' => array( MBS_Color_Helper::class, 'sanitize' ),
		) );
		register_setting( 'mbs_appearance', 'mbs_setting_appearance_button_bg', array(
			'sanitize_callback' => array( MBS_Color_Helper::class, 'sanitize' ),
		) );
		register_setting( 'mbs_appearance', 'mbs_setting_appearance_button_text', array(
			'sanitize_callback' => array( MBS_Color_Helper::class, 'sanitize' ),
		) );
		register_setting( 'mbs_appearance', 'mbs_setting_appearance_link', array(
			'sanitize_callback' => array( MBS_Color_Helper::class, 'sanitize' ),
		) );

		// ── PRO tokens (16) ──────────────────────────────────────────────────
		// C-005: Wrapped in mbs_is_pro() so FREE-tier users cannot write these
		// options via a crafted POST to options.php.
		// C-001: Token names updated to D-2 canonical set — must match the keys
		// read by mbs_output_color_vars() in bookshowroom.php exactly.
		if ( mbs_is_pro() ) {
			$pro_tokens = array(
				'navy',
				'navy_dark',
				'lavender',
				'teal_pale',
				'lavender_pale',
				'beige',
				'slate',
				'mist',
				'pro_bg',
				'pro_text',
				'coming_soon_bg',
				'coming_soon_text',
				'card_bg',
				'border',
				'watermark_text',
				'star',
			);
			foreach ( $pro_tokens as $token ) {
				register_setting( 'mbs_appearance', 'mbs_setting_appearance_' . $token, array(
					'sanitize_callback' => array( MBS_Color_Helper::class, 'sanitize' ),
				) );
			}
		}

		// ── Other settings ───────────────────────────────────────────────────
		// Custom CSS moved to Settings -> Advanced (power-user / developer feature).

		// Dark mode toggle — boolean; clamp to 0 or 1 (ST-002).
		register_setting( 'mbs_appearance', 'mbs_setting_appearance_dark_mode', array(
			'sanitize_callback' => 'absint',
		) );

		// ── F-002: Layout geometry ───────────────────────────────────────────────
		// FREE: gap preset. PRO: column count + radius preset.
		register_setting( 'mbs_appearance', 'mbs_setting_appearance_gap', array(
			'sanitize_callback' => 'sanitize_key',
		) );
		if ( mbs_is_pro() ) {
			register_setting( 'mbs_appearance', 'mbs_setting_appearance_columns', array(
				'sanitize_callback' => function( $val ) {
					$int = absint( $val );
					return ( $int >= 1 && $int <= 6 ) ? $int : '';
				},
			) );
			register_setting( 'mbs_appearance', 'mbs_setting_appearance_radius', array(
				'sanitize_callback' => 'sanitize_key',
			) );
		}

		// ── Power Badge settings (Sprint POWERBADGE) ──────────────────────────
		// badge_position: available to all registered tiers (FREE+).
		register_setting( 'mbs_appearance', 'mbs_setting_appearance_badge_position', array(
			'sanitize_callback' => function( $val ) {
				$allowed = array( 'bottom-right', 'bottom-left', 'bottom-center' );
				return in_array( $val, $allowed, true ) ? $val : 'bottom-right';
			},
		) );
		// badge_enabled: PRO/PUB only -- opt-in to displaying the badge.
		if ( mbs_is_pro() ) {
			register_setting( 'mbs_appearance', 'mbs_setting_appearance_badge_enabled', array(
				'sanitize_callback' => 'absint',
			) );
		}

		// DISPLAY-2: Bestseller rank threshold.
		register_setting( 'mbs_appearance', 'mbs_setting_bestseller_rank_threshold', array(
			'sanitize_callback' => function( $val ) {
				$n = (int) $val;
				return ( $n >= 1 && $n <= 1000000 ) ? $n : 100;
			},
		) );
	}

	/**
	 * Enqueue Appearance tab assets when this tab is active.
	 *
	 * Called by MBS_Settings::enqueue_assets() for every tab object.
	 * Only fires when $current_tab matches this tab's slug.
	 *
	 * @param string $current_tab The active tab slug.
	 * @return void
	 */
	public function enqueue( string $current_tab ): void {
		if ( 'appearance' !== $current_tab ) {
			return;
		}

		wp_enqueue_style(
			'mbs-admin-settings-appearance',
			plugins_url( 'assets/css/mbs-admin-settings-appearance.css', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin-settings' ),
			MBS_VERSION
		);

		// Component stylesheets — split from mbs-admin-settings-appearance.css (Session 100).
		foreach ( array( 'dark-mode', 'tab-layout', 'live-preview', 'accordion' ) as $component ) {
			wp_enqueue_style(
				'mbs-appearance-' . $component,
				plugins_url( 'assets/css/admin/appearance/appearance-' . $component . '.css', MBS_DIR . 'bookshowroom.php' ),
				array( 'mbs-admin-settings-appearance' ),
				MBS_VERSION
			);
		}

		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );

		// Phase 4a: Appearance tab JS (PLG-038). Depends on jquery + wp-color-picker.
		wp_enqueue_script(
			'mbs-admin-appearance',
			plugins_url( 'assets/js/adminjs/admin-appearance.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery', 'wp-color-picker', 'wp-i18n' ),
			MBS_VERSION,
			true
		);

		wp_set_script_translations( 'mbs-admin-appearance', 'my-book-showroom', plugin_dir_path( MBS_DIR . 'bookshowroom.php' ) . 'languages' );

		// ── Book Picker: gather published and draft books for the live preview ──
		$_mbs_books_data   = array();
		$_mbs_book_posts   = get_posts( array(
			'post_type'      => MBS_POST_TYPE,
			'post_status'    => array( 'publish', 'draft' ),
			'posts_per_page' => 50,
			'orderby'        => 'title',
			'order'          => 'ASC',
			'no_found_rows'  => true,
		) );
		foreach ( $_mbs_book_posts as $_mbs_book ) {
			$_mbs_author_terms = wp_get_post_terms( $_mbs_book->ID, MBS_TAX_AUTHOR, array( 'fields' => 'names' ) );
			$_mbs_author_str   = ( ! is_wp_error( $_mbs_author_terms ) && ! empty( $_mbs_author_terms ) )
				? implode( ', ', $_mbs_author_terms )
				: '';
			$_mbs_cover_url    = get_the_post_thumbnail_url( $_mbs_book->ID, 'medium' ); // R5-exempt: appearance preview admin UI
			$_mbs_books_data[] = array(
				'id'     => $_mbs_book->ID,
				'title'  => $_mbs_book->post_title,
				'author' => $_mbs_author_str,
				'cover'  => $_mbs_cover_url ? $_mbs_cover_url : '',
			);
		}

		wp_localize_script( 'mbs-admin-appearance', 'MBS_Appearance', array(
			'defaults' => array(
				// FREE_DEFAULTS is the single source of truth — shared with
				// render() so PHP and JS never disagree on baseline colors.
				'free' => self::FREE_DEFAULTS,
			),
			'strings' => array(
				'confirmReset' => __( 'Reset all colors to defaults?', 'my-book-showroom' ),
			),
			'books'        => $_mbs_books_data,
			'fallbackCover' => esc_url( MBS_ASSETS_URL . 'dummy/cover-fallback.jpg' ),
		) );

		// F-002: Layout customization live preview.
		wp_enqueue_script(
			'mbs-admin-customization',
			plugins_url( 'assets/js/adminjs/mbs-admin-customization.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery' ),
			MBS_VERSION,
			true
		);
		wp_localize_script( 'mbs-admin-customization', 'MBS_Customization', array(
			'isPro'   => mbs_is_pro(),
			'presets' => array(
				'gap' => array(
					'compact'     => '0.5rem',
					'comfortable' => '1rem',
					'spacious'    => '1.75rem',
				),
				'radius' => array(
					'square'  => '0px',
					'slight'  => '4px',
					'rounded' => '12px',
				),
			),
		) );
	}

	/**
	 * Render the Appearance tab.
	 *
	 * R-09: Thin orchestrator — all section HTML lives in MBS_Tab_Appearance_Render.
	 *
	 * @return void
	 */
	public function render(): void {
		// RF-009: $is_pro internalized in each child render class.
		?>
		<div class="mbs-tab-appearance">
			<h2><?php esc_html_e( 'Appearance Settings', 'my-book-showroom' ); ?></h2>

			<div class="mbs-appearance-layout">

				<!-- ── Column 1: Color controls ─────────────────────────── -->
				<div class="mbs-appearance-controls">
					<?php MBS_Tab_Appearance_Render::render_free_colors(); ?>
					<?php MBS_Tab_Appearance_Render::render_pro_colors(); ?>
					<?php MBS_Tab_Appearance_Render::render_dark_mode(); ?>
					<?php /* Custom CSS moved to Settings -> Advanced */ ?>
					<?php MBS_Tab_Appearance_Render::render_layout_customization(); ?>
				<?php MBS_Tab_Appearance_Render::render_badge_settings(); ?>
				<?php MBS_Tab_Appearance_Render::render_bestseller_settings(); // DISPLAY-2 ?>
				<?php /* Analytics moved to Settings -> Advanced (R-ADV-02). */ ?>
				<?php MBS_Tab_Appearance_Render::render_action_row(); ?>
				</div>

				<!-- ── Column 2: Live Preview (sticky on very wide screens) ── -->
				<?php MBS_Tab_Appearance_Render::render_live_preview(); ?>

			</div>
		</div>
		<?php
	}
}
