<?php
/**
 * File Path: includes/admin/class-mbs-admin-assets.php
 *
 * Book Editor Admin Asset Enqueuing
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Admin_Assets {

	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	/**
	 * Enqueue admin assets for the Book Editor (Context 2) only.
	 *
	 * Settings-page assets (mbs-admin-settings.css / .js) are handled
	 * exclusively by MBS_Settings::enqueue_assets() to avoid double-enqueue.
	 *
	 * C-006: admin-license.js removed. License AJAX JS belongs only on
	 * the Settings → License tab (enqueued by MBS_Settings::enqueue_assets()).
	 * It added unnecessary page weight to every book editor screen and registered
	 * click handlers that could never fire in that context.
	 *
	 * REF-28: Moved here from MBS_Admin::enqueue_admin_assets().
	 *
	 */
	public function enqueue( $hook ): void {
		// S13-14: Drag-and-drop book ordering on the book list screen.
		if ( 'edit.php' === $hook ) {
			global $post_type;
			if ( $post_type === MBS_POST_TYPE ) {
				wp_enqueue_script( 'jquery-ui-sortable' );
				// mbs-admin.js uses MBS_AdminUtils.escAttr; ensure the utility
				// library is loaded on the books list page (not just the Book Editor).
				wp_enqueue_script(
					'mbs-admin-utils',
					plugins_url( 'assets/js/adminjs/mbs-admin-utils.js', MBS_DIR . 'bookshowroom.php' ),
					array(),
					(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/mbs-admin-utils.js' ) ?: MBS_VERSION ),
					true
				);
				wp_enqueue_script(
					'mbs-admin',
					plugins_url( 'assets/js/mbs-admin.js', MBS_DIR . 'bookshowroom.php' ),
					array( 'jquery', 'jquery-ui-sortable', 'mbs-admin-utils', 'wp-i18n' ),
					MBS_VERSION,
					true
				);
				wp_set_script_translations( 'mbs-admin', 'my-book-showroom', MBS_DIR . 'languages' );
				wp_localize_script(
					'mbs-admin',
					'MBS_AdminData',
					array(
						'orderNonce' => wp_create_nonce( 'mbs_book_order_nonce' ),
						'isPro'      => mbs_is_pro(),
					)
				);
			}
		}

		// Only load on MBS Book editor screens (Context 2).
		if ( ! in_array( $hook, array( 'post-new.php', 'post.php' ), true ) ) {
			return;
		}

		global $post_type;
		if ( $post_type !== MBS_POST_TYPE ) {
			return;
		}

		// PLG-005 (extended): Each book-editor asset uses its own filemtime() so
		// that changing any individual file busts only that file's browser cache
		// without requiring a MBS_VERSION bump or touching the orchestrator.

		// Enqueue main admin stylesheet.
		wp_enqueue_style(
			'mbs-admin',
			plugins_url( 'assets/css/mbs-admin.css', MBS_DIR . 'bookshowroom.php' ),
			array(),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'css/mbs-admin.css' ) ?: MBS_VERSION )
		);

		// Shared sortable-UI styles — .mbs-drag-handle, .mbs-reorder-controls,
		// .mbs-sortable-placeholder. Loaded on every Book admin page so all
		// sortable lists have consistent base styles regardless of active tab.
		wp_enqueue_style(
			'mbs-sortable-styles',
			plugins_url( 'assets/css/admin/mbs-sortable.css', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-admin' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'css/admin/mbs-sortable.css' ) ?: MBS_VERSION )
		);

		// Hide the standard WP "Add title" bar — mbs_book_title in the Book Header metabox
		// is the canonical title and syncs to post_title on save (D-5).
		wp_add_inline_style( 'mbs-admin', '#titlediv { display: none !important; }' );

		// Enqueue wp.media + MBS video/image uploader handler.
		wp_enqueue_media();
		wp_enqueue_script(
			'mbs-media-uploader',
			plugins_url( 'assets/js/mbs-media-uploader.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery', 'wp-i18n' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/mbs-media-uploader.js' ) ?: MBS_VERSION ),
			true
		);
		wp_set_script_translations( 'mbs-media-uploader', 'my-book-showroom', MBS_DIR . 'languages' );

		// Core suggest for Author(s) autocomplete.
		wp_enqueue_script( 'suggest' );
		wp_enqueue_style( 'suggest' );

		// Shared admin JS utilities — escHtml/escAttr used by child modules.
		wp_enqueue_script(
			'mbs-admin-utils',
			plugins_url( 'assets/js/adminjs/mbs-admin-utils.js', MBS_DIR . 'bookshowroom.php' ),
			array(),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/mbs-admin-utils.js' ) ?: MBS_VERSION ),
			true
		);

		// Shared sortable-list factory — MBS.SortableList.create().
		// Provides the canonical drag-and-drop + up/down-arrow-fallback module
		// consumed by all sortable admin lists (format rows, social links, etc.).
		wp_enqueue_script(
			'mbs-sortable-list',
			plugins_url( 'assets/js/adminjs/mbs-sortable-list.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery', 'jquery-ui-sortable', 'mbs-admin-utils' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/mbs-sortable-list.js' ) ?: MBS_VERSION ),
			true
		);

		// Book editor orchestrator.
		// C2-002: jquery-ui-sortable added — required for per-book section-order
		// drag-and-drop in the Section Order metabox.
		wp_enqueue_script(
			'mbs-book-editor',
			plugins_url( 'assets/js/mbs-book-editor.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'jquery', 'jquery-ui-sortable', 'mbs-admin-utils' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/mbs-book-editor.js' ) ?: MBS_VERSION ),
			true
		);

		// Child modules — book editor context only.
		// mbs-admin-repeater: namespace initializer; per-module files depend on it.
		wp_enqueue_script(
			'mbs-admin-repeater',
			plugins_url( 'assets/js/adminjs/admin-repeater.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-repeater.js' ) ?: MBS_VERSION ),
			true
		);

		// Repeater sub-modules — split from admin-repeater.js (Session 94).
		$repeater_modules = array(
			'mbs-repeater', 'mbs-contributors', 'mbs-link-icon-helper', 'mbs-buy-links',
			'mbs-book-cover', 'mbs-format-buy-links', 'mbs-awards',
			'mbs-reader-platforms',
		);
		foreach ( $repeater_modules as $module ) {
			wp_enqueue_script(
				'mbs-admin-' . $module,
				plugins_url( 'assets/js/adminjs/repeater/' . $module . '.js', MBS_DIR . 'bookshowroom.php' ),
				array( 'mbs-admin-repeater' ),
				(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/repeater/' . $module . '.js' ) ?: MBS_VERSION ),
				true
			);
			// i18n wiring — only modules with user-visible strings (mbs-format-buy-links has none).
			if ( in_array( $module, array( 'mbs-repeater', 'mbs-awards', 'mbs-buy-links', 'mbs-contributors', 'mbs-reader-platforms', 'mbs-book-cover', 'mbs-link-icon-helper' ), true ) ) {
				wp_set_script_translations( 'mbs-admin-' . $module, 'my-book-showroom', MBS_DIR . 'languages' );
			}
		}

		// Localize shared data for admin repeater modules (icon URLs, PRO flag).
		wp_localize_script(
			'mbs-admin-repeater',
			'MBS_ADMIN',
			array(
				'retailersUrl' => plugins_url( 'assets/images/retailers/', MBS_DIR . 'bookshowroom.php' ),
				'siteIconUrl'  => ( function() {
					$_icon_id  = (int) get_option( 'site_icon' );
					if ( ! $_icon_id ) { return ''; }
					$_icon_url = get_site_icon_url( 32 );
					if ( ! $_icon_url ) {
						$_icon_url = wp_get_attachment_url( $_icon_id ) ?: '';
					}
					return $_icon_url;
				} )(),
				'isPro'        => mbs_is_pro(),
			)
		);

		wp_enqueue_script(
			'mbs-admin-endorsements',
			plugins_url( 'assets/js/adminjs/admin-endorsements.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor', 'wp-i18n' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-endorsements.js' ) ?: MBS_VERSION ),
			true
		);
		wp_set_script_translations( 'mbs-admin-endorsements', 'my-book-showroom', MBS_DIR . 'languages' );

		wp_enqueue_script(
			'mbs-admin-authors',
			plugins_url( 'assets/js/adminjs/admin-authors.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor', 'suggest', 'wp-i18n' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-authors.js' ) ?: MBS_VERSION ),
			true
		);
		wp_set_script_translations( 'mbs-admin-authors', 'my-book-showroom', MBS_DIR . 'languages' );

		// GC1-5 (I-001/I-012): wp-i18n added as dep; wp_set_script_translations() registered.
		wp_enqueue_script(
			'mbs-admin-validation',
			plugins_url( 'assets/js/adminjs/admin-validation.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor', 'wp-i18n' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-validation.js' ) ?: MBS_VERSION ),
			true
		);
		wp_set_script_translations( 'mbs-admin-validation', 'my-book-showroom', MBS_DIR . 'languages' );

		// FV-015: Pass currency config to price-validation JS modules.
		$_mbs_currency = mbs_get_setting( 'general', 'currency', 'USD' );
		wp_localize_script(
			'mbs-admin-validation',
			'MBS_PriceConfig',
			array(
				'currency'      => $_mbs_currency,
				'isZeroDecimal' => MBS_Formatting::is_zero_decimal_currency( $_mbs_currency ),
				'maxPrice'      => MBS_Formatting::get_max_price( $_mbs_currency ),
			)
		);
		unset( $_mbs_currency );

		wp_enqueue_script(
			'mbs-admin-dirty-state',
			plugins_url( 'assets/js/adminjs/admin-dirty-state.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-dirty-state.js' ) ?: MBS_VERSION ),
			true
		);

		// Social Share Text UX — pill insert + live preview.
		wp_enqueue_script(
			'mbs-admin-share-text',
			plugins_url( 'assets/js/adminjs/admin-share-text.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor', 'wp-i18n' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-share-text.js' ) ?: MBS_VERSION ),
			true
		);
		wp_set_script_translations( 'mbs-admin-share-text', 'my-book-showroom', MBS_DIR . 'languages' );

		// Coming Soon UX — auto-check on future date, preorder row toggle, URL validation.
		wp_enqueue_script(
			'mbs-admin-coming-soon',
			plugins_url( 'assets/js/adminjs/admin-coming-soon.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor', 'wp-i18n' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-coming-soon.js' ) ?: MBS_VERSION ),
			true
		);
		wp_set_script_translations( 'mbs-admin-coming-soon', 'my-book-showroom', MBS_DIR . 'languages' );
		wp_localize_script(
			'mbs-admin-coming-soon',
			'MBS_ComingSoonData',
			array( 'isPro' => mbs_is_pro() )
		);

		// Publisher autocomplete — live suggestions from existing publisher values.
		wp_enqueue_script( 'jquery-ui-autocomplete' );
		wp_enqueue_script(
			'mbs-admin-publisher',
			plugins_url( 'assets/js/adminjs/admin-publisher.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor', 'jquery-ui-autocomplete' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-publisher.js' ) ?: MBS_VERSION ),
			true
		);

		// Localize shared AJAX nonce — used by publisher autocomplete and other child scripts.
		wp_localize_script(
			'mbs-book-editor',
			'MBS_BookEditorAjax',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'mbs_book_editor_ajax' ),
			)
		);

		// F-026-7/b: Broadcast buttons -- only when PRO and broadcast enabled.
		if ( mbs_is_pro() && '1' === mbs_get_setting( 'email', 'broadcast_enabled', '0' ) ) {
			wp_enqueue_style(
				'mbs-admin-broadcast',
				plugins_url( 'assets/css/mbs-admin-broadcast.css', MBS_DIR . 'bookshowroom.php' ),
				array(),
				(string) ( @filemtime( MBS_ASSETS_DIR . 'css/mbs-admin-broadcast.css' ) ?: MBS_VERSION )
			);
			wp_enqueue_script(
				'mbs-broadcast',
				plugins_url( 'assets/js/adminjs/mbs-broadcast.js', MBS_DIR . 'bookshowroom.php' ),
				array( 'jquery', 'wp-i18n' ),
				(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/mbs-broadcast.js' ) ?: MBS_VERSION ),
				true
			);
			wp_set_script_translations( 'mbs-broadcast', 'my-book-showroom', MBS_DIR . 'languages' );
			wp_localize_script( 'mbs-broadcast', 'MBS_Broadcast', array(
				'ajaxurl'    => admin_url( 'admin-ajax.php' ),
				'adminEmail' => sanitize_email( get_option( 'admin_email' ) ),
			) );
		}

		// Sprint 171: Look Inside DOCX upload + live word count.
		// Enqueue unconditional -- TinyMCE re-init and word count serve all tiers.
		// Localize only for PRO (nonce exposes tier-gated AJAX endpoint).
		wp_enqueue_script(
			'mbs-admin-look-inside',
			plugins_url( 'assets/js/adminjs/admin-look-inside.js', MBS_DIR . 'bookshowroom.php' ),
			array( 'mbs-book-editor', 'wp-i18n' ),
			(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-look-inside.js' ) ?: MBS_VERSION ),
			true
		);
		// Z-002: wp_set_script_translations() MUST be here, outside the mbs_is_pro() gate.
		wp_set_script_translations( 'mbs-admin-look-inside', 'my-book-showroom', MBS_DIR . 'languages' );
		if ( mbs_is_pro() ) {
			wp_localize_script(
				'mbs-admin-look-inside',
				'MBS_LookInsideAjax',
				array(
					'ajaxUrl' => admin_url( 'admin-ajax.php' ),
					'nonce'   => wp_create_nonce( 'mbs_look_inside_nonce' ),
					'isPro'   => true,
				)
			);
		}

		// PRO/PUB icon picker — custom retailer/platform icon via WP media library.
		if ( mbs_is_pro() || mbs_is_pub() ) {
			wp_enqueue_script(
				'mbs-admin-icon-picker',
				plugins_url( 'assets/js/adminjs/mbs-admin-icon-picker.js', MBS_DIR . 'bookshowroom.php' ),
				array( 'mbs-book-editor', 'wp-i18n' ),
				(string) ( @filemtime( MBS_ASSETS_DIR . 'js/adminjs/mbs-admin-icon-picker.js' ) ?: MBS_VERSION ),
				true
			);
			wp_set_script_translations( 'mbs-admin-icon-picker', 'my-book-showroom', MBS_DIR . 'languages' );
		}

		// Book Club Resources (PRO) -- discussion questions sortable + media picker.
		// Enqueued here (not in MBS_Metabox_Book_Club) because the handler class is
		// only instantiated at render time, after admin_enqueue_scripts fires.
		if ( mbs_is_pro() ) {
			wp_enqueue_script(
				'mbs-admin-book-club',
				plugins_url( 'assets/js/adminjs/admin-book-club.js', MBS_DIR . 'bookshowroom.php' ),
				array( 'jquery', 'jquery-ui-sortable', 'media-editor', 'wp-i18n' ),
				filemtime( MBS_ASSETS_DIR . 'js/adminjs/admin-book-club.js' ),
				true
			);
			wp_set_script_translations( 'mbs-admin-book-club', 'my-book-showroom', MBS_DIR . 'languages' );
		}
	}
}
